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
030831fcbcf4345eb18a9bb2dc535e95
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; import static java.util.Arrays.fill; import static java.util.Arrays.binarySearch; import static java.util.Arrays.sort; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { try { if (new File("input.txt").exists()) System.setIn(new FileInputStream("input.txt")); } catch (SecurityException e) {} long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); in.close(); } /*************************************************************** * Solution **************************************************************/ final int INF = Integer.MAX_VALUE / 2; int vNum, eNum; DijkstraGraph g; int[] dist; void solve() throws IOException { vNum = nextInt(); eNum = nextInt(); int from = nextInt() - 1; g = new DijkstraGraph(vNum, 2 * eNum); for (int i = 0; i < eNum; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int w = nextInt(); g.add(u, v, w); g.add(v, u, w); } int l = nextInt(); dijkstraRMQ(from); // System.out.println(Arrays.toString(dist)); Set<Item> set = new HashSet<Main.Item>(); boolean[] used = new boolean [vNum]; for (int v = 0; v < vNum; v++) { used[v] = true; if (dist[v] == l) { set.add(new Item(v, v, 0)); } for (int i = g.head[v]; i != 0; i = g.next[i]) { int x = g.vert[i]; if (used[x]) { continue; } int w = g.cost[i]; int dv = l - dist[v]; int dx = l - dist[x]; if (dist[v] >= l && dist[x] >= l) { continue; } else if (dist[x] >= l) { if (dv < w) { set.add(new Item(v, x, dv)); } } else if (dist[v] >= l) { if (dx < w) { set.add(new Item(v, x, w - dx)); } } else { if (dv + dx == w) { set.add(new Item(v, x, dv)); } else if (dv + dx < w) { set.add(new Item(v, x, dv)); set.add(new Item(v, x, w - dx)); } } } } // System.out.println(set); out.println(set.size()); } void dijkstraRMQ(int v) { dist = new int [vNum]; RMQ rmq = new RMQ(vNum); boolean[] used = new boolean [vNum]; fill(dist, INF); rmq.set(v, dist[v] = 0); while ((v = rmq.minInd(0, vNum - 1)) != -1) { rmq.set(v, INF); used[v] = true; for (int i = g.head[v]; i != 0; i = g.next[i]) { int x = g.vert[i]; int w = g.cost[i]; if (!used[x] && dist[x] > dist[v] + w) rmq.set(x, dist[x] = dist[v] + w); } } } class Item { int u, v; int dist; Item(int u, int v, int dist) { this.u = u; this.v = v; this.dist = dist; } @Override public boolean equals(Object obj) { if (obj instanceof Item) { Item item = (Item) obj; return u == item.u && v == item.v && dist == item.dist; } return false; } @Override public int hashCode() { return (u * 1638911) ^ (v * 237239) ^ dist; } @Override public String toString() { return u + " " + v + " " + dist; } } class DijkstraGraph { int[] head; int[] next; int[] vert; int[] cost; int cnt = 1; DijkstraGraph(int vNum, int eNum) { head = new int [vNum]; next = new int [eNum + 1]; vert = new int [eNum + 1]; cost = new int [eNum + 1]; } void add(int u, int v, int w) { next[cnt] = head[u]; vert[cnt] = v; cost[cnt] = w; head[u] = cnt++; } } class RMQ { int[] val; int[] ind; int n; RMQ(int n) { this.n = n; val = new int [2 * n]; ind = new int [2 * n]; fill(val, INF); for (int i = 0; i < n; i++) ind[i + n] = i; } void set(int i, int v) { val[i += n] = v; for (i >>= 1; i > 0; i >>= 1) { int add = val[2 * i] < val[2 * i + 1] ? 0 : 1; val[i] = val[2 * i + add]; ind[i] = ind[2 * i + add]; } } int minInd(int l, int r) { l += n; r += n; double min = INF; int ret = -1; while (l <= r) { if (l % 2 == 1 && min > val[l]) { min = val[l]; ret = ind[l]; } if (r % 2 == 0 && min > val[r]) { min = val[r]; ret = ind[r]; } l = (l + 1) / 2; r = (r - 1) / 2; } return ret; } } /*************************************************************** * Input **************************************************************/ BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } int[] nextIntArray(int size) throws IOException { int[] ret = new int [size]; for (int i = 0; i < size; i++) ret[i] = nextInt(); return ret; } long[] nextLongArray(int size) throws IOException { long[] ret = new long [size]; for (int i = 0; i < size; i++) ret[i] = nextLong(); return ret; } double[] nextDoubleArray(int size) throws IOException { double[] ret = new double [size]; for (int i = 0; i < size; i++) ret[i] = nextDouble(); return ret; } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } /*************************************************************** * Output **************************************************************/ void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { if (array == null || array.length == 0) return; for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { if (array == null || array.length == 0) return; boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { if (collection == null || collection.isEmpty()) return; boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } /*************************************************************** * Utility **************************************************************/ static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } static void checkMemory() { System.err.println(memoryStatus()); } static long prevTimeStamp = Long.MIN_VALUE; static void updateTimer() { prevTimeStamp = System.currentTimeMillis(); } static long elapsedTime() { return (System.currentTimeMillis() - prevTimeStamp); } static void checkTimer() { System.err.println(elapsedTime() + " ms"); } }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≤ n ≤ 105, , 1 ≤ s ≤ n) — the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≤ l ≤ 109) — the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number — the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
a63de93a4311b35e840c6ba003ce7d86
train_002.jsonl
1326899100
A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missiles. The exact position of the Super Duper Secret Missile Silos is kept secret but Bob managed to get hold of the information. That information says that all silos are located exactly at a distance l from the capital. The capital is located in the city with number s.The documents give the formal definition: the Super Duper Secret Missile Silo is located at some place (which is either city or a point on a road) if and only if the shortest distance from this place to the capital along the roads of the country equals exactly l.Bob wants to know how many missile silos are located in Berland to sell the information then to enemy spies. Help Bob.
256 megabytes
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StreamTokenizer; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.PriorityQueue; public class D { private static void relax(long[] d, int u, int v, int w){ if(d[v] > d[u] + w) { d[v] = d[u] + w; // P[v] = u; } } private static long[] deikstra(ArrayList<int[]>[] mas, int x) { int n = mas.length; boolean[] used = new boolean[n]; long[] d = new long[n]; Arrays.fill(d, Long.MAX_VALUE); d[x] = 0; used = new boolean[n]; //int[] = {value_d, numb_of_vertex} PriorityQueue<long[]> pq = new PriorityQueue<long[]>(1000, new Comparator<long[]>() { public int compare(long[] mas1, long[] mas2) { return mas1[0] >= mas2[0] ? 1 : mas1[0] == mas2[0] ? 0 : -1; } }); pq.add(new long[] {0, x}); while(!pq.isEmpty()) { long[] curv = pq.remove(); if(used[(int) curv[1]])continue; used[(int) curv[1]] = true; for(int[] i : mas[(int) curv[1]]) { if(used[i[0]])continue; relax(d, (int)curv[1], i[0], i[1]); // u, v, w (weight) pq.add(new long[] {d[i[0]], i[0]}); } } return d; } private static int n, m, s, l; private static ArrayList<int[]>[] mas; public static void main(String[] args) throws Exception { n = nextInt(); m = nextInt(); s = nextInt()-1; mas = new ArrayList[n]; for(int i =0 ; i<n; i++) { mas[i] = new ArrayList<int[]>(); } for(int i = 0; i<m; i++) { int u = nextInt()-1, v = nextInt()-1, c = nextInt(); mas[u].add(new int[] {v, c}); mas[v].add(new int[] {u, c}); } l = nextInt(); if(l == 0)exit(1); long[] res = deikstra(mas, s); // for(int i =0 ; i<res.length; i++) { // out.print(res[i] + " "); // } // out.println(); // out.flush(); int ans = 0; for(int i = 0; i<n; i++) { if(res[i] == l)ans++; } for(int i = 0; i<n; i++ ) { for(int[] el : mas[i]) { if(el[0] < i)continue; long dist1 = res[i]; long dist2 = res[el[0]]; if(dist1 >= l && dist2 >= l)continue; if(dist1 < l && dist2 < l) { if((dist1 + dist2 + el[1]) == 2*l)ans++; else if((dist1 + dist2 + el[1]) > 2*l)ans+=2; } else { long dist = Math.min(dist1, dist2); if(dist < l && l < (dist + el[1]))ans++; } } } println(ans); } ///////////////////////////////////////////////////////////////// // IO ///////////////////////////////////////////////////////////////// private static StreamTokenizer in; private static PrintWriter out; private static BufferedReader inB; private static boolean FILE=false; private static int nextInt() throws Exception{ in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception{ in.nextToken(); return in.sval; } static{ try { out = new PrintWriter(FILE ? (new FileOutputStream("output.txt")) : System.out); inB = new BufferedReader(new InputStreamReader(FILE ? new FileInputStream("input.txt") : System.in)); } catch(Exception e) {e.printStackTrace();} in = new StreamTokenizer(inB); } ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // pre - written ///////////////////////////////////////////////////////////////// private static void println(Object o) throws Exception { out.println(o); out.flush(); } private static void exit(Object o) throws Exception { println(o); exit(); } private static void exit() { System.exit(0); } private static final int INF = Integer.MAX_VALUE; private static final int MINF = Integer.MIN_VALUE; ////////////////////////////////////////////////////////////////// }
Java
["4 6 1\n1 2 1\n1 3 3\n2 3 1\n2 4 1\n3 4 1\n1 4 2\n2", "5 6 3\n3 1 1\n3 2 1\n3 4 1\n3 5 1\n1 2 6\n4 5 8\n4"]
2 seconds
["3", "3"]
NoteIn the first sample the silos are located in cities 3 and 4 and on road (1, 3) at a distance 2 from city 1 (correspondingly, at a distance 1 from city 3).In the second sample one missile silo is located right in the middle of the road (1, 2). Two more silos are on the road (4, 5) at a distance 3 from city 4 in the direction to city 5 and at a distance 3 from city 5 to city 4.
Java 6
standard input
[ "data structures", "graphs", "dfs and similar", "shortest paths" ]
c3c3ac7a8c9d2ce142e223309ab005e6
The first line contains three integers n, m and s (2 ≤ n ≤ 105, , 1 ≤ s ≤ n) — the number of cities, the number of roads in the country and the number of the capital, correspondingly. Capital is the city no. s. Then m lines contain the descriptions of roads. Each of them is described by three integers vi, ui, wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1000), where vi, ui are numbers of the cities connected by this road and wi is its length. The last input line contains integer l (0 ≤ l ≤ 109) — the distance from the capital to the missile silos. It is guaranteed that: between any two cities no more than one road exists; each road connects two different cities; from each city there is at least one way to any other city by the roads.
1,900
Print the single number — the number of Super Duper Secret Missile Silos that are located in Berland.
standard output
PASSED
c965b348dece06d5cade3bdbe303804c
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.io.*; //import java.util.*; public class PC_499 { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(in.readLine()); int m=Integer.parseInt(in.readLine()); int[] a=new int[n]; String[] inp=in.readLine().split(" "); for(int i=0;i<n;i++)a[i]=Integer.parseInt(inp[i]); int[] b=new int[n]; inp=in.readLine().split(" "); for(int i=0;i<n;i++)b[i]=Integer.parseInt(inp[i]); double h=1e9; double l=0; double pmid=0; double thresh=1e-6; int flag=0; while(l<=h){ double mid=(h+l)/2; double w=m+mid; for(int i=0;i<n;i++){ if(i==0){ if(a[i]==1 || b[0]==1){ l=h+1; pmid=0; flag=1; break; } w=w-w/a[i]; } /* else if(i==n-1){ w=w-w/b[i]; } */ else{ w=w-w/b[i]; w=w-w/a[i]; if(a[i]==1 || b[i]==1)flag=1; } } w=w-w/b[0]; //System.out.println(l+" "+h+" "+mid+" "+pmid+" "+(w-m)); if(w-m>0){ h=mid; } else{ l=mid; } if(Math.abs(mid-pmid)<thresh)break; pmid=mid; if(flag==1)break; } if(flag==1)System.out.println(-1); else System.out.println(pmid); } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 11
standard input
[ "binary search", "greedy", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
b24c1a2db47ee499f4d7eb3484d67fd6
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*;import java.io.*;import java.math.*; public class Main { public static void process()throws IOException { int n=ni(); double wt=nd(),a[]=new double[n],b[]=new double[n],k=1.0d; for(int i=0;i<n;i++) a[i]=nd(); for(int i=0;i<n;i++) b[i]=nd(); for(int i=0;i<n;i++){ if(a[i]==1.0d || b[i]==1.0d){ pn(-1); return; } } for(int i=0;i<n;i++){ k*=(a[i]-1.0d)/a[i]; k*=(b[i]-1.0d)/b[i]; } if(k==0){ pn(-1); return; } double res=wt*(k-1.0d)/k; res*=-1.0d; if(res<0){ pn(-1); return; } pn(res); } static AnotherReader sc; static PrintWriter out; public static void main(String[]args)throws IOException { out = new PrintWriter(System.out); sc=new AnotherReader(); boolean oj = true; oj = System.getProperty("ONLINE_JUDGE") != null; if(!oj) sc=new AnotherReader(100); long s = System.currentTimeMillis(); int t=1; //t=ni(); while(t-->0) process(); out.flush(); if(!oj) System.out.println(System.currentTimeMillis()-s+"ms"); System.out.close(); } static void pn(Object o){out.println(o);} static void p(Object o){out.print(o);} static void pni(Object o){out.println(o);System.out.flush();} static int ni()throws IOException{return sc.nextInt();} static long nl()throws IOException{return sc.nextLong();} static double nd()throws IOException{return sc.nextDouble();} static String nln()throws IOException{return sc.nextLine();} static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));} static boolean multipleTC=false; static long mod=(long)1e9+7l; static void r_sort(int arr[],int n){ Random r = new Random(); for (int i = n-1; i > 0; i--){ int j = r.nextInt(i+1); int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } Arrays.sort(arr); } static long mpow(long x, long n) { if(n == 0) return 1; if(n % 2 == 0) { long root = mpow(x, n / 2); return root * root % mod; }else { return x * mpow(x, n - 1) % mod; } } static long mcomb(long a, long b) { if(b > a - b) return mcomb(a, a - b); long m = 1; long d = 1; long i; for(i = 0; i < b; i++) { m *= (a - i); m %= mod; d *= (i + 1); d %= mod; } long ans = m * mpow(d, mod - 2) % mod; return ans; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// static class AnotherReader{BufferedReader br; StringTokenizer st; AnotherReader()throws FileNotFoundException{ br=new BufferedReader(new InputStreamReader(System.in));} AnotherReader(int a)throws FileNotFoundException{ br = new BufferedReader(new FileReader("input.txt"));} String next()throws IOException{ while (st == null || !st.hasMoreElements()) {try{ st = new StringTokenizer(br.readLine());} catch (IOException e){ e.printStackTrace(); }} return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next());} long nextLong() throws IOException {return Long.parseLong(next());} double nextDouble()throws IOException { return Double.parseDouble(next()); } String nextLine() throws IOException{ String str = ""; try{ str = br.readLine();} catch (IOException e){ e.printStackTrace();} return str;}} ///////////////////////////////////////////////////////////////////////////////////////////////////////////// }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 11
standard input
[ "binary search", "greedy", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
16d007184746408c8b5c1ae3e59be2ba
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; import java.io.*; public class Q2 { static Print print; public static void main(String args[]) throws Exception { Scan scan = new Scan(); print = new Print(); int N=scan.scanInt(); double M=scan.scanDouble(); double temp=M; double arr[][]=new double[N][2]; for(int i=0;i<N;i++) { arr[i][0]=scan.scanInt(); } for(int i=0;i<N;i++) { arr[i][1]=scan.scanInt(); } int prev=0; for(int i=N-1;i>=0;i--) { if(arr[prev][1]<=1 || arr[i][0]<=1) { print.println(-1); print.close(); System.exit(0); } double fuel=M/(arr[prev][1]-1); M+=fuel; fuel=M/(arr[i][0]-1); M+=fuel; prev=i; } print.println(M-temp); print.close(); } public static class Print { private final BufferedWriter bw; public Print() { this.bw = new BufferedWriter(new OutputStreamWriter(System.out)); } public void print(Object object) throws IOException { bw.append("" + object); } public void println(Object object) throws IOException { print(object); bw.append("\n"); } public void close() throws IOException { bw.close(); } } static class Scan { private byte[] buf = new byte[1024 * 1024 * 4]; private int index; private InputStream in; private int total; public Scan() { in = System.in; } public int scan() throws IOException { if (total < 0) throw new InputMismatchException(); if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) return -1; } return buf[index++]; } public int scanInt() throws IOException { 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(); } else throw new InputMismatchException(); } return neg * integer; } public double scanDouble() throws IOException { double doub = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n) && n != '.') { if (n >= '0' && n <= '9') { doub *= 10; doub += n - '0'; n = scan(); } else throw new InputMismatchException(); } if (n == '.') { n = scan(); double temp = 1; while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { temp /= 10; doub += (n - '0') * temp; n = scan(); } else throw new InputMismatchException(); } } return doub * neg; } public long scanLong() throws IOException { long ret = 0; long c = scan(); while (c <= ' ') { c = scan(); } boolean neg = (c == '-'); if (neg) { c = scan(); } do { ret = ret * 10 + c - '0'; } while ((c = scan()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public String scanString() throws IOException { StringBuilder sb = new StringBuilder(); int n = scan(); while (isWhiteSpace(n)) n = scan(); while (!isWhiteSpace(n) || n == ' ') { sb.append((char) n); n = scan(); } return sb.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; return false; } } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 11
standard input
[ "binary search", "greedy", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
4f661b01b1ff695b717dcf515ff3dd4e
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class ewmath3attackofthebinarysearch { public static void main(String[] args) { Scanner msc = new Scanner(System.in); int planets = msc.nextInt(); int cargo = msc.nextInt(); int[] takeOff = new int[planets]; int[] landing = new int[planets]; for(int i = 0 ; i < planets ; i++){ takeOff[i] = msc.nextInt(); } for(int i = 0 ; i < planets ; i++){ landing[i] = msc.nextInt(); } if(!canGo(planets, cargo, takeOff, landing, 2e9)) { System.out.println(-1); return; } double lo = 0; double hi = 1e9; for(int i = 0 ; i < 150 ; i++){ double gss = (lo + hi) / 2; if(canGo(planets, cargo, takeOff, landing, gss)) { hi = gss; } else { lo = gss; } } System.out.println(hi); } static boolean canGo(int planets, int cargo, int[] takeOff, int[] landing, double fuel) { double mass = cargo + fuel; for(int i = 0 ; i < planets ; i++){ mass -= mass/takeOff[i]; mass -= mass/landing[(i + 1) % planets]; } return mass >= cargo; } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 11
standard input
[ "binary search", "greedy", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
3d72a4d9eb04cac2998aaa648c895ada
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
// package cp; import java.io.*; import java.util.*; public class Cf_three { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); Readers.init(System.in); int n=Readers.nextInt(); int m=Readers.nextInt(); long[] a=new long[n]; long[] b=new long[n]; for (int i = 0; i < b.length; i++) { a[i]=Readers.nextLong(); } for (int i = 0; i < b.length; i++) { b[i]=Readers.nextLong(); } double ans=m; for (int i = 0; i < b.length; i++) { ans*=(1L*((double)(a[i])/(double)(a[i]-1)) *((double)(b[i])/(double)(b[i]-1))); } // System.out.println(ans); Double inf=Double.POSITIVE_INFINITY; if(ans<m || (inf==ans))System.out.println(-1); else System.out.println(ans-m); out.flush(); } } class Readers { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next()); } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 11
standard input
[ "binary search", "greedy", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
b4fe01ed172ee3229c3dff2a8de9d742
train_002.jsonl
1532617500
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
256 megabytes
import java.util.*; public class fly{ static int numPlanet; static int weight; static int [] arrTakeoff; static int [] arrLanding; public static void main (String args []){ Scanner sc = new Scanner(System.in); numPlanet = sc.nextInt(); weight = sc.nextInt(); arrTakeoff = new int [numPlanet]; arrLanding = new int [numPlanet]; for(int i = 0; i < numPlanet; i++){ arrTakeoff[i] = sc.nextInt(); } for(int i = 0; i < numPlanet; i++){ arrLanding[i] = sc.nextInt(); } double lowNum = 0; double highNum = 1e9; if(!checkTrip(2e9)){ System.out.println("-1"); return; } for(int i = 0; i < 200; i++){ double guess = (lowNum + highNum) / 2; if(checkTrip(guess)){ highNum = guess; } else{ lowNum = guess; } } System.out.printf("%.9f\n", lowNum); } public static boolean checkTrip (double fuel){ double simWeight = weight + fuel; for(int i = 0; i < numPlanet; i++){ simWeight -= (simWeight/arrTakeoff[i]); if(i+1 >= 0 && i+1 <= numPlanet - 1){ simWeight -= simWeight/arrLanding[i+1]; } else{ simWeight -= simWeight/arrLanding[0]; } } return simWeight >= weight; } public static boolean checkEqual (double lowNum, double highNum){ return Math.abs(lowNum - highNum) <= 1e-9; } }
Java
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
1 second
["10.0000000000", "-1", "85.4800000000"]
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
Java 11
standard input
[ "binary search", "greedy", "math" ]
d9bd63e03bf51ed87ba73cd15e8ce58d
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
1,500
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
standard output
PASSED
3c34e96c4e6b3774b66589f7a7954afa
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Random; import java.util.Scanner; import java.util.StringTokenizer; public class Main { static final long MOD=998244353; 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 s=new FastReader(); int n=s.nextInt(); long a[]=new long[n]; long b[]=new long[n]; for(int i=0;i<a.length;i++) { a[i]=s.nextLong(); } for(int i=0;i<a.length;i++) { b[i]=s.nextLong(); } for(int i=0;i<a.length;i++) { a[i]=a[i]*(i+1)*(n-i); } shuffleArray(a); shuffleArray(b); Arrays.sort(a); Arrays.sort(b); long sum=0; for(int i=0;i<a.length;i++) { sum+=(a[i]%MOD)*(b[n-i-1]%MOD); sum%=MOD; } System.out.println(sum); } static void shuffleArray(long[] arr){ int n = arr.length; Random rnd = new Random(); for(int i=0; i<n; ++i){ long tmp = arr[i]; int randomPos = i + rnd.nextInt(n-i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer — the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
8c84fb68c9f5f17cbbed5f231761fc28
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.awt.image.AreaAveragingScaleFilter; import java.io.*; import java.math.BigInteger; import java.sql.Array; import java.util.*; import java.util.StringTokenizer; public class l{ static class pair implements Comparable<pair>{ int v,idx; static int n; pair(int a ,int b,int n){ v=a; idx=b; this.n=n; } @Override public int compareTo(pair pair) { return Long.compare(v*1l*(n-idx)*(idx+1),pair.v*1l*(n-pair.idx)*(pair.idx+1)); } } static int mod=998244353; public static void main (String[]args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); int n = sc.nextInt(); Long[]a = new Long[n]; Integer[]b = new Integer[n]; PriorityQueue<pair>pq= new PriorityQueue<>(); for (int i =0;i<n;i++){ a[i]=sc.nextLong()*(1l*n-i)*(1l*i+1); } Arrays.sort(a); for (int i =0;i<n;i++){ b[i]=sc.nextInt(); } Arrays.sort(b); // int[]nb= new int[n]; long ans =0; for (int i =0;i<n;i++){ ans+=(a[i]%mod)*b[n-i-1]; ans%=mod; } // for (int i =n-1;i>=0;i--){ // nb[pq.poll().idx]=b[i]; // } // long[]mul = new long[n]; // for (int i =0;i<n;i++){ // mul[i]=1l*a[i]*nb[i]; // mul[i]%=mod; // } // for (int i =0;i<n;i++){ // ans+=(mul[i]*((i+1)*(n-i)))%mod; // ans%=mod; // //ans+=(mul[i]*(n-i))%mod; // } pw.println(ans%mod); pw.flush(); } static int gcd(int a ,int b){ if (a==0)return b; return gcd(b%a,a); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer — the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
cafd5574e78b3fc472f1469f9dd9face
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=1; while(T-->0) { int n=input.nextInt(); long a[]=new long[n]; long b[]=new long[n]; long m=998244353; for(int i=0;i<n;i++) { a[i]=input.nextInt(); a[i]=a[i]*(long)(n-i)*(long)(i+1); } mergeSort(a,0,n-1); for(int i=0;i<n;i++) { b[i]=input.nextInt(); } mergeSort(b,0,n-1); long sum=0; for(int i=0;i<n;i++) { long ans=1; ans=(ans%m*a[i]%m)%m; ans=(ans%m*b[n-1-i]%m)%m; sum=(sum%m+ans%m)%m; } out.println(sum); } out.close(); } public static void mergeSort(long a[],int p,int r) { if(p<r) { int q=(p+r)/2; mergeSort(a,p,q); mergeSort(a,q+1,r); merge(a,p,q,r); } } public static void merge(long a[],int p,int q,int r) { int n1=q-p+2; long L[]=new long[n1]; int n2=r-q+1; long R[]=new long[n2]; for(int i=p;i<=q;i++) { L[i-p]=a[i]; } L[n1-1]=Long.MAX_VALUE; for(int i=q+1;i<=r;i++) { R[i-q-1]=a[i]; } R[n2-1]=Long.MAX_VALUE; int x=0,y=0; for(int i=p;i<=r;i++) { if(L[x]<=R[y]) { a[i]=L[x]; x++; } else { a[i]=R[y]; y++; } } } 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
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer — the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
95c4ca8236f0a8dd4f96cf0b5bc093bd
train_002.jsonl
1557844500
You are given two arrays $$$a$$$ and $$$b$$$, both of length $$$n$$$.Let's define a function $$$f(l, r) = \sum\limits_{l \le i \le r} a_i \cdot b_i$$$.Your task is to reorder the elements (choose an arbitrary order of elements) of the array $$$b$$$ to minimize the value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$. Since the answer can be very large, you have to print it modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author koneko096 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); ETwoArraysAndSumOfFunctions solver = new ETwoArraysAndSumOfFunctions(); solver.solve(1, in, out); out.close(); } static class ETwoArraysAndSumOfFunctions { private static int MOD = 998244353; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[] a = new long[n]; int[] b = new int[n]; for (int i = 0; i < n; i++) { long cnt = (long) (i + 1) * (n - i); a[i] = cnt * in.nextInt(); } Arrays.sort(a); for (int i = 0; i < n; i++) { b[i] = -in.nextInt(); } Arrays.sort(b); long ans = 0; for (int i = 0; i < n; i++) { ans = add(ans, mul(a[i] % MOD, -b[i])); } out.print(ans); } private long add(long x, long y) { return (x + y) % MOD; } private long mul(long x, long y) { return x * y % MOD; } } static class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n1 8 7 2 4\n9 7 2 9 3", "1\n1000000\n1000000", "2\n1 3\n4 2"]
2 seconds
["646", "757402647", "20"]
null
Java 8
standard input
[ "sortings", "greedy", "math" ]
93431bdae447bb96a2f0f5fa0c6e11e0
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$ and $$$b$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^6$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_j \le 10^6$$$), where $$$b_j$$$ is the $$$j$$$-th element of $$$b$$$.
1,600
Print one integer — the minimum possible value of $$$\sum\limits_{1 \le l \le r \le n} f(l, r)$$$ after rearranging elements of $$$b$$$, taken modulo $$$998244353$$$. Note that you should minimize the answer but not its remainder.
standard output
PASSED
a7c610c99cf84a73143d525d30d2b7bc
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.LinkedList; import java.util.Collections; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author vivek0464 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); solver.solve(1, in, out); out.close(); } static class TaskE { static int maxn = (int) (2e5 + 5); static int n; static int m; static int a; static int b; static int c; static ArrayList<ArrayList<Integer>> ar = new ArrayList<ArrayList<Integer>>(maxn); static ArrayList<Integer> da = new ArrayList<Integer>(maxn); static ArrayList<Integer> db = new ArrayList<Integer>(maxn); static ArrayList<Integer> dc = new ArrayList<Integer>(maxn); static ArrayList<Long> pr = new ArrayList<Long>(maxn); public void bfs(int u, int cnt) { LinkedList<Integer> q = new LinkedList<Integer>(); q.add(u); if (cnt == 0) { da.set(u, 0); while (!q.isEmpty()) { int p = q.pollFirst(); for (int v : ar.get(p)) { if (da.get(v) == maxn) { da.set(v, da.get(p) + 1); q.addLast(v); } } } } else if (cnt == 1) { db.set(u, 0); while (!q.isEmpty()) { int p = q.pollFirst(); for (int v : ar.get(p)) { if (db.get(v) == maxn) { db.set(v, db.get(p) + 1); q.addLast(v); } } } } else if (cnt == 2) { dc.set(u, 0); while (!q.isEmpty()) { int p = q.pollFirst(); for (int v : ar.get(p)) { if (dc.get(v) == maxn) { dc.set(v, dc.get(p) + 1); q.addLast(v); } } } } } public void solve(int testNumber, InputReader in, PrintWriter out) { int t = in.nextInt(); while (t-- > 0) { n = in.nextInt(); m = in.nextInt(); a = in.nextInt(); b = in.nextInt(); c = in.nextInt(); pr.clear(); pr.add((long) 0); for (int i = 0; i < m; i++) { pr.add((long) in.nextInt()); } ar.clear(); for (int i = 0; i <= n; i++) { ar.add(new ArrayList<Integer>()); } for (int i = 1; i <= m; i++) { int u = in.nextInt(); int v = in.nextInt(); ar.get(u).add(v); ar.get(v).add(u); } Collections.sort(pr); for (int i = 1; i <= m; i++) { pr.set(i, pr.get(i - 1) + pr.get(i)); } da.clear(); db.clear(); dc.clear(); for (int i = 0; i <= n; i++) { da.add(maxn); db.add(maxn); dc.add(maxn); } bfs(a, 0); bfs(b, 1); bfs(c, 2); // out.print(db.get(2)); long ans = Long.MAX_VALUE; for (int i = 1; i <= n; i++) { if (da.get(i) + db.get(i) + dc.get(i) > m) continue; ans = Math.min(ans, (long) pr.get(db.get(i)) + (long) pr.get(da.get(i) + db.get(i) + dc.get(i))); } out.println(ans); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
bf5098882c437fac3cfc46a3f99e91a9
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.AbstractCollection; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; inputClass in = new inputClass(inputStream); PrintWriter out = new PrintWriter(outputStream); EWeightsDistributing solver = new EWeightsDistributing(); solver.solve(1, in, out); out.close(); } static class EWeightsDistributing { static EWeightsDistributing.Node[] graph; static boolean[] visited; static void bfs(int src, int[] dist) { visited[src] = true; dist[src] = 0; LinkedList<Integer> l = new LinkedList<>(); l.add(src); while (!l.isEmpty()) { int a = l.pollFirst(); for (int i : graph[a].edges) { if (!visited[i]) { visited[i] = true; dist[i] = dist[a] + 1; l.addLast(i); } } } } public void solve(int testNumber, inputClass sc, PrintWriter out) { int t = sc.nextInt(); while (t > 0) { t--; int n = sc.nextInt(); graph = new EWeightsDistributing.Node[n]; visited = new boolean[n]; for (int i = 0; i < n; i++) { graph[i] = new EWeightsDistributing.Node(); graph[i].edges = new ArrayList<>(); } int m = sc.nextInt(); int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; int c = sc.nextInt() - 1; Integer[] price = new Integer[m]; for (int i = 0; i < m; i++) { price[i] = sc.nextInt(); } for (int i = 0; i < m; i++) { int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; graph[u].edges.add(v); graph[v].edges.add(u); } Arrays.sort(price); int[] dist1 = new int[n]; int[] dist2 = new int[n]; int[] dist3 = new int[n]; bfs(a, dist1); Arrays.fill(visited, false); bfs(b, dist2); Arrays.fill(visited, false); bfs(c, dist3); long[] pref = new long[m]; pref[0] = price[0]; for (int i = 1; i < m; i++) { pref[i] = pref[i - 1] + price[i]; } if (a == b && a == c) { out.println(0); continue; } if (a == c) { out.println(pref[dist1[b] - 1] * 2); continue; } if (a == b) { out.println(pref[dist3[b] - 1]); continue; } if (b == c) { out.println(pref[dist1[b] - 1]); continue; } long ans = Long.MAX_VALUE; for (int i = 0; i < n; i++) { long sum; if (dist2[i] + dist3[i] + dist1[i] - 1 >= m) { continue; } if (dist2[i] == 0) { sum = pref[dist3[i] + dist1[i] - 1]; } else { sum = pref[dist2[i] - 1] + pref[dist2[i] + dist3[i] + dist1[i] - 1]; } ans = Math.min(ans, sum); } out.println(ans); } } public static class Node { ArrayList<Integer> edges; } } static class inputClass { BufferedReader br; StringTokenizer st; public inputClass(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
c9d002729d9981b6ff4de6e570ea2666
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { static Scanner sc = new Scanner(System.in); static PrintWriter out = new PrintWriter(System.out); static final int INF = (int) 1e9 + 10; static ArrayList<Integer> adj[]; static int[] bfs(int n, int s) { Queue<Integer> q = new LinkedList<>(); int[] dist = new int[n]; Arrays.fill(dist, INF); dist[s] = 0; q.add(s); while (!q.isEmpty()) { int u = q.poll(); for (int v : adj[u]) { if (dist[v] == INF) { q.add(v); dist[v] = dist[u] + 1; } } } return dist; } static void solve() throws Exception { int n = sc.nextInt(), m = sc.nextInt(); int a = sc.nextInt() - 1, b = sc.nextInt() - 1, c = sc.nextInt() - 1; Long cost[] = new Long[m]; long presum[] = new long[m + 1]; adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); } for (int i = 0; i < m; i++) { cost[i] = sc.nextLong(); } Arrays.sort(cost); for (int i = 1; i <= m; i++) { presum[i] = cost[i - 1] + presum[i - 1]; } for (int i = 0; i < m; i++) { int u = sc.nextInt() - 1, v = sc.nextInt() - 1; adj[u].add(v); adj[v].add(u); } int[] da = bfs(n, a), db = bfs(n, b), dc = bfs(n, c); long ans = Long.MAX_VALUE; // a -> i , i -> b, b -> i, i -> c for (int idx, i = 0; i < n; i++) { if ((idx = da[i] + db[i] + dc[i]) > m) continue; ans = Math.min(ans, presum[idx] + presum[db[i]]); } out.println(ans); } public static void main(String[] args) throws Exception { int tc = sc.nextInt(); while (tc-- > 0) { solve(); } out.close(); } } class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public Long nextLong() throws IOException { return Long.parseLong(next()); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
d922455b3f7dcf4de7d7a4bb24dd8407
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; @SuppressWarnings("unchecked") public class Problem_E { static final long INF = Long.MAX_VALUE / 2; static int N, M, A, B, C; static List<Integer>[] G; public static int[] bfs(int S) { int[] d = new int[N + 1]; Arrays.fill(d, -1); Queue<Integer> q = new LinkedList<>(); d[S] = 0; q.offer(S); while (!q.isEmpty()) { int x = q.poll(); for (int y : G[x]) { if (d[y] == -1) { d[y] = d[x] + 1; q.offer(y); } } } return d; } public static void shuffle(int[] A) { for (int i = 0; i < A.length; i++) { int j = (int)(i * Math.random()); int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } public static void main(String[] args) { InputReader in = new InputReader(); StringBuilder out = new StringBuilder(); int T = in.nextInt(); while (T-- > 0) { N = in.nextInt(); M = in.nextInt(); A = in.nextInt(); B = in.nextInt(); C = in.nextInt(); int[] P = new int[M + 1]; for (int i = 1; i <= M; i++) { P[i] = in.nextInt(); } shuffle(P); Arrays.sort(P); long[] psum = new long[M + 1]; for (int i = 1; i <= M; i++) { psum[i] = psum[i - 1] + P[i]; } G = new List[N + 1]; for (int i = 1; i <= N; i++) { G[i] = new ArrayList<>(); } for (int i = 0; i < M; i++) { int u = in.nextInt(); int v = in.nextInt(); G[u].add(v); G[v].add(u); } int[] bfs_A = bfs(A); int[] bfs_B = bfs(B); int[] bfs_C = bfs(C); long ans = INF; for (int i = 1; i <= N; i++) { int sum = bfs_A[i] + bfs_B[i] + bfs_C[i]; if (sum > M) { continue; } ans = Math.min(ans, psum[sum] + psum[bfs_B[i]]); } out.append(ans).append('\n'); } System.out.print(out); } static class InputReader { public BufferedReader reader; public StringTokenizer st; public InputReader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String next() { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(nextLine()); } return st.nextToken(); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
e913d86f0ec6c8de074572dc228f2a32
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.StringTokenizer; public class Round636E { public static LinkedList<Integer>[] adj; // public static int[] dis_c; public static void bfs1(int c, int[] dis_c) { int n = adj.length; // dis_c = new int[n]; Arrays.fill(dis_c, -1); LinkedList<Pair> q = new LinkedList<>(); q.add(new Pair(c, 0)); // dis_c[c] = 0; while(!q.isEmpty()) { Pair top = q.removeFirst(); int len = top.y; if(dis_c[top.x] == -1) { for(Integer y : adj[top.x]) { if(dis_c[y] == -1) { q.addLast(new Pair(y, len + 1)); // dis_c[y] = len + 1; } } dis_c[top.x] = len; } } } // public static LinkedList<Integer> Path(int src, int des) { // if(src == des) { // LinkedList<Integer> te = new LinkedList<Integer>(); // te.add(src); return te; // } // ArrayList<HashSet<Integer>> helper = new ArrayList<>(); // int n = adj.length; // boolean[] visited = new boolean[n]; //// visited[src] = true; // HashSet<Integer> temp = new HashSet<Integer>(); temp.add(src); helper.add(temp); // int ptr = 0; // while(ptr < helper.size()) { // HashSet<Integer> top = helper.get(ptr++); // temp = new HashSet<Integer>(); // boolean flag = false; // for(Integer x : top) { // if(!visited[x]) { // for(Integer y : adj[x]) { // if(!visited[y]) { // temp.add(y); // if(y == des) { // flag = true; // } // } // } // visited[x] = true; // } // } // helper.add(temp); // if(flag) { // break; // } // } // int pos = ptr - 1; // LinkedList<Integer> path = new LinkedList<Integer>(); // path.addLast(des); // int last = des; // while(pos >= 0) { // for(Integer x : adj[last]) { // if(helper.get(pos).contains(x)) { // path.addLast(x); // pos--; // last = x; // break; // } // } // } // return path; // } public static void solve() { int t = s.nextInt(); while(t-- > 0) { int n = s.nextInt(); int m = s.nextInt(); int a = s.nextInt() - 1; int b = s.nextInt() - 1; int c = s.nextInt() - 1; adj = new LinkedList[n]; for(int i = 0; i < n; i++) adj[i] = new LinkedList<Integer>(); Integer[] p = new Integer[m]; for(int i = 0; i < m; i++) { p[i] = s.nextInt(); } for(int i = 0; i < m; i++) { int u = s.nextInt() - 1; int v = s.nextInt() - 1; adj[u].add(v); adj[v].add(u); } Arrays.sort(p); long[] pref = new long[m]; pref[0] = p[0]; for(int i = 1; i < m; i++) { pref[i] = pref[i - 1] + p[i]; } int[] dis_A = new int[n]; bfs1(a, dis_A); int[] dis_B = new int[n]; bfs1(b, dis_B); int[] dis_C = new int[n]; bfs1(c, dis_C); long ans = inf; for(int i = 0; i < n; i++) { int ax = dis_A[i]; int bx = dis_B[i]; int cx = dis_C[i]; long tempans = ax + bx + cx - 1 < 0 ? 0 : (ax + bx + cx - 1 >= m ? inf : pref[ax + bx + cx - 1]); tempans += bx == 0 ? 0 : pref[bx - 1]; ans = Long.min(ans, tempans); } out.println(ans); } } public static long inf = (long)1e16; public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(); solve(); out.close(); } public static class Pair{ int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static FastReader s; public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
ecd51e220667320d3bb55eb09c383875
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class E { static class Reader { BufferedReader br; StringTokenizer st; public Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static Reader in; int n, m, a, b, c; int[] p, dista, distb, distc; long[] pre; List<Integer>[] adj; boolean[] vis; void bfsa(int v) { Arrays.fill(vis, false); Queue<Integer> Q = new LinkedList<>(); dista[v] = 0; Q.add(v); vis[v] = true; while (!Q.isEmpty()) { int node = Q.poll(); for (int neigh : adj[node]) { if (vis[neigh]) continue; Q.add(neigh); dista[neigh] = Math.min(dista[neigh], dista[node] + 1); vis[neigh] = true; } } } void bfsb(int v) { Arrays.fill(vis, false); Queue<Integer> Q = new LinkedList<>(); distb[v] = 0; Q.add(v); vis[v] = true; while (!Q.isEmpty()) { int node = Q.poll(); for (int neigh : adj[node]) { if (vis[neigh]) continue; Q.add(neigh); distb[neigh] = Math.min(distb[neigh], distb[node] + 1); vis[neigh] = true; } } } void bfsc(int v) { Arrays.fill(vis, false); Queue<Integer> Q = new LinkedList<>(); distc[v] = 0; Q.add(v); vis[v] = true; while (!Q.isEmpty()) { int node = Q.poll(); for (int neigh : adj[node]) { if (vis[neigh]) continue; Q.add(neigh); distc[neigh] = Math.min(distc[neigh], distc[node] + 1); vis[neigh] = true; } } } void init() { int T = in.nextInt(); while (T-- > 0) { n = in.nextInt(); m = in.nextInt(); a = in.nextInt()-1; b = in.nextInt()-1; c = in.nextInt()-1; adj = new ArrayList[n]; p = new int[m]; dista = new int[n]; distb = new int[n]; distc = new int[n]; vis = new boolean[n]; pre = new long[m]; for(int i = 0;i < n;i++) { adj[i] = new ArrayList<>(); dista[i] = Integer.MAX_VALUE; distb[i] = Integer.MAX_VALUE; distc[i] = Integer.MAX_VALUE; } for (int i = 0; i < m; i++) { p[i] = in.nextInt(); } for (int i = 0; i < m; i++) { int u = in.nextInt() - 1; int v = in.nextInt() - 1; // System.out.println("got input u = "+u+" v = "+v); adj[u].add(v); adj[v].add(u); } Arrays.sort(p); pre[0] = p[0]; for (int i = 1; i < m; i++) { pre[i] = pre[i - 1] + p[i]; } // CommonDebugCode.printArray(pre); // System.out.println(); bfsa(a); bfsb(b); bfsc(c); // CommonDebugCode.printArray(dista); // CommonDebugCode.printArray(distb); // CommonDebugCode.printArray(distc); long min =Long.MAX_VALUE; if(dista[b] + distc[b] - 1 >= 0 && dista[b] + distc[b] - 1 < m) min = pre[dista[b] + distc[b] - 1]; for (int i = 0; i < n; i++) { long val = 0; int count = 0; // System.out.println("at i = "+i); if (distb[i] != 0){ val += (2*pre[distb[i] - 1]); count = distb[i]-1; } // System.out.println("\tcount2 = "+count); if(dista[i] + distc[i] + count >= m && dista[i] + distc[i] + count >= 0) continue; val += pre[dista[i] + distc[i] + count] - pre[count]; min = Math.min(val,min); // System.out.println("\tval = "+val); } System.out.println(min); } } public static void main(String[] args) throws Exception { // Scanner in = new Scanner(System.in); in = new Reader(); new E().init(); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
358dd2f6497c5bc540e3428eb1e2d073
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.awt.Point; public class Main { //static final long MOD = 998244353L; //static final long INF = 1000000000000000007L; static final long MOD = 1000000007L; static final int INF = 1000000007; public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter pw = new PrintWriter(System.out); int Q = sc.ni(); for (int q = 0; q < Q; q++) { int N = sc.ni(); int M = sc.ni(); int A = sc.ni()-1; int B = sc.ni()-1; int C = sc.ni()-1; long[] P = new long[M]; for (int i = 0; i < M; i++) P[i] = sc.nl(); P = shuffle(P); Arrays.sort(P); long[] pref = new long[M+1]; for (int i = 1; i <= M; i++) pref[i] = pref[i-1]+P[i-1]; ArrayList<Integer>[] graph = new ArrayList[N]; for (int i = 0; i < N; i++) graph[i] = new ArrayList<Integer>(); for (int i = 0; i < M; i++) { int n1 = sc.ni()-1; int n2 = sc.ni()-1; graph[n1].add(n2); graph[n2].add(n1); } int[] distA = new int[N]; Arrays.fill(distA,Integer.MAX_VALUE); ArrayDeque<Integer> bfs = new ArrayDeque<Integer>(); bfs.add(A); distA[A] = 0; while (!bfs.isEmpty()) { int node = bfs.poll(); for (int next: graph[node]) { if (distA[next] == Integer.MAX_VALUE) { distA[next] = distA[node]+1; bfs.add(next); } } } int[] distC = new int[N]; Arrays.fill(distC,Integer.MAX_VALUE); bfs.add(C); distC[C] = 0; while (!bfs.isEmpty()) { int node = bfs.poll(); for (int next: graph[node]) { if (distC[next] == Integer.MAX_VALUE) { distC[next] = distC[node]+1; bfs.add(next); } } } int[] distB = new int[N]; Arrays.fill(distB,Integer.MAX_VALUE); bfs.add(B); distB[B] = 0; while (!bfs.isEmpty()) { int node = bfs.poll(); for (int next: graph[node]) { if (distB[next] == Integer.MAX_VALUE) { distB[next] = distB[node]+1; bfs.add(next); } } } long ans = Long.MAX_VALUE; //A -> D -> B -> D -> C for (int D = 0; D < N; D++) { if (distA[D]+distB[D]+distC[D] <= M) { ans = Math.min(ans,pref[distA[D]+distB[D]+distC[D]]+pref[distB[D]]); } } pw.println(ans); } pw.close(); } public static long dist(long[] p1, long[] p2) { return (Math.abs(p2[0]-p1[0])+Math.abs(p2[1]-p1[1])); } //Find the GCD of two numbers public static long gcd(long a, long b) { if (a < b) return gcd(b,a); if (b == 0) return a; else return gcd(b,a%b); } //Fast exponentiation (x^y mod m) public static long power(long x, long y, long m) { if (y < 0) return 0L; long ans = 1; x %= m; while (y > 0) { if(y % 2 == 1) ans = (ans * x) % m; y /= 2; x = (x * x) % m; } return ans; } public static int[] shuffle(int[] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static long[] shuffle(long[] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); long temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[][] shuffle(int[][] array) { Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } return array; } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] a, int[] b) { return a[0]-b[0]; //ascending order } }); return array; } public static long[][] sort(long[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); long[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<long[]>() { @Override public int compare(long[] a, long[] b) { if (a[0] < b[0]) return -1; else if (a[0] > b[0]) return 1; else return 0; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { 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 ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } double nd() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
c88493158820ea5627cf24cf50fb8a59
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
// Utilities import java.io.*; import java.util.*; public class Main { static int T, N, M, a, b, c; static ArrayList<Integer>[] adj; static int[] da, db, dc; static long[] p, s; static long min; public static void main(String[] args) throws IOException { T = in.iscan(); for (int t = 0; t < T; t++) { N = in.iscan(); M = in.iscan(); a = in.iscan(); b = in.iscan(); c = in.iscan(); p = new long[M+1]; s = new long[M+1]; for (int i = 1; i <= M; i++) p[i] = in.iscan(); Arrays.sort(p); for (int i = 1; i <= M; i++) s[i] = s[i-1] + p[i]; adj = new ArrayList[N+1]; for (int i = 0; i <= N; i++) adj[i] = new ArrayList(); int x, y; for (int i = 0; i < M; i++) { x = in.iscan(); y = in.iscan(); adj[x].add(y); adj[y].add(x); } da = new int[N+1]; db = new int[N+1]; dc = new int[N+1]; Arrays.fill(da, Integer.MAX_VALUE); Arrays.fill(db, Integer.MAX_VALUE); Arrays.fill(dc, Integer.MAX_VALUE); da[a] = 0; db[b] = 0; dc[c] = 0; for (int i = 0; i <= 2; i++) bfs(i); min = Long.MAX_VALUE; for (int i = 1; i <= N; i++) { if (da[i] + db[i] + dc[i] <= M) min = Math.min(min, s[db[i]] + s[da[i]+db[i]+dc[i]]); } out.println(min); } out.close(); } static void bfs(int idx) { // idx: 0 = a, 1 = b, 2 = c; Queue<Integer> q = new LinkedList<Integer>(); if (idx == 0) q.add(a); else if (idx == 1) q.add(b); else q.add(c); while (!q.isEmpty()) { int cur = q.poll(); for (int u : adj[cur]) { if (idx == 0 && da[cur] + 1 < da[u]) { da[u] = da[cur] + 1; q.add(u); } else if (idx == 1 && db[cur] + 1 < db[u]) { db[u] = db[cur] + 1; q.add(u); } else if (idx == 2 && dc[cur] + 1 < dc[u]) { dc[u] = dc[cur] + 1; q.add(u); } } } } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static int gcd (int a, int b) { return b == 0 ? a : gcd (b, a % b); } public static int lcm (int a, int b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
4b47dcf75d1911cb56f821fb3a6f0794
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.util.Random; import java.io.InputStream; /** * Built using CHelper plug-in Actual solution is at the top * * @author NMouad21 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); EWeightsDistributing solver = new EWeightsDistributing(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class EWeightsDistributing { public final void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int m = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); long[] p = in.nextLongArrayOneBased(m); ArrayShuffler.shuffle(p); Arrays.sort(p); for (int i = 1; i <= m; i++) { p[i] += p[i - 1]; } int[][] e = in.nextIntMatrix(m, 2); int[][] g = GraphUtils.packUndirectedUnweighted(e, n); int[] aDist = bfs(n, m, g, a); int[] bDist = bfs(n, m, g, b); int[] cDist = bfs(n, m, g, c); long ans = 2 * p[m]; for (int i = 1; i <= n; i++) { int edgesCount = aDist[i] + cDist[i] + bDist[i]; if (edgesCount > m) { continue; } ans = Math.min(ans, p[bDist[i]] + p[edgesCount]); } out.println(ans); } private final int[] bfs(int n, int m, int[][] g, int a) { int[] dist = new int[n + 1]; int[] queue = new int[n + 1]; int addPt = 0, pollPt = 0; Arrays.fill(dist, m + 1); queue[addPt++] = a; dist[a] = 0; while (addPt > pollPt) { int u = queue[pollPt++]; for (int v : g[u]) { if (dist[v] == m + 1) { dist[v] = dist[u] + 1; queue[addPt++] = v; } } } return dist; } } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1 << 16]; private int curChar; private int numChars; public InputReader() { this.stream = System.in; } public InputReader(final InputStream stream) { this.stream = stream; } private final int read() { if (this.numChars == -1) { throw new UnknownError(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException ex) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public final int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) {} byte sgn = 1; if (c == 45) { // 45 == '-' sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9' res *= 10; res += c - 48; // 48 == '0' c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public final long nextLong() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) {} byte sgn = 1; if (c == 45) { // 45 == '-' sgn = -1; c = this.read(); } long res = 0; while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9' res *= 10L; res += c - 48; // 48 == '0' c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public final String next() { int c; while (isSpaceChar(c = this.read())) {} StringBuilder result = new StringBuilder(); result.appendCodePoint(c); while (!isSpaceChar(c = this.read())) { result.appendCodePoint(c); } return result.toString(); } private static final boolean isSpaceChar(final int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; // 32 == ' ', 10 == '\n', 13 == '\r', 9 == '\t' } public final int[][] nextIntMatrix(final int n, final int m) { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { arr[i][j] = nextInt(); } } return arr; } public final long[] nextLongArrayOneBased(final int n) { long[] ret = new long[n + 1]; for (int i = 1; i <= n; i++) { ret[i] = nextLong(); } return ret; } } static class ArrayShuffler { private static Random r = new Random(System.nanoTime() * 21); private ArrayShuffler() { throw new RuntimeException("DON'T"); } public static long[] shuffle(long[] arr, int from, int to) { int n = to - from + 1; for (int i = from; i <= to; i += 4) { int p = r.nextInt(n + 1) + from; if (p <= to) { long temp = arr[i]; arr[i] = arr[p]; arr[p] = temp; } } return arr; } public static long[] shuffle(long[] arr) { return shuffle(arr, 0, arr.length - 1); } } static final class GraphUtils { private GraphUtils() { throw new RuntimeException("DON'T"); } public static final int[][] packUndirectedUnweighted(int[][] edges, int n) { int[][] g = new int[n + 1][]; int[] size = new int[n + 1]; for (int[] edge : edges) { ++size[edge[0]]; ++size[edge[1]]; } for (int i = 0; i <= n; i++) { g[i] = new int[size[i]]; } for (int[] edge : edges) { g[edge[0]][--size[edge[0]]] = edge[1]; g[edge[1]][--size[edge[1]]] = edge[0]; } return g; } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
f5da049c91ce6704b5e5677689e344a3
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x1343E { static int N; public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int C = Integer.parseInt(st.nextToken()); int[] prices = new int[M]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < M; i++) prices[i] = Integer.parseInt(st.nextToken()); sort(prices); LinkedList<Integer>[] edges = new LinkedList[N+1]; for(int i=1; i <= N; i++) edges[i] = new LinkedList<Integer>(); for(int i=0; i < M; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); edges[a].add(b); edges[b].add(a); } long[] psums = new long[M+1]; for(int i=1; i <= M; i++) psums[i] = psums[i-1]+prices[i-1]; long res = Long.MAX_VALUE; int[] d1 = bfs(A, edges); int[] d2 = bfs(B, edges); int[] d3 = bfs(C, edges); for(int v=1; v <= N; v++) if(d1[v]+d2[v]+d3[v] <= M) res = Math.min(res, psums[d2[v]]+psums[d1[v]+d2[v]+d3[v]]); sb.append(res+"\n"); } System.out.print(sb); } public static int[] bfs(int start, LinkedList<Integer>[] edges) { int[] dist = new int[N+1]; Arrays.fill(dist, -1); dist[start] = 0; Queue<Integer> q = new LinkedList<Integer>(); q.add(start); while(q.size() > 0) { int curr = q.poll(); for(int next: edges[curr]) if(dist[next] == -1) { dist[next] = dist[curr]+1; q.add(next); } } return dist; } public static void sort(int[] arr) { //stable heap sort PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for(int a: arr) pq.add(a); for(int i=0; i < arr.length; i++) arr[i] = pq.poll(); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
361f22d8725636bcb40b7aa1d9702e5a
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x1343E { static int N; public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); int C = Integer.parseInt(st.nextToken()); int[] prices = new int[M]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < M; i++) prices[i] = Integer.parseInt(st.nextToken()); sort(prices); LinkedList<Integer>[] edges = new LinkedList[N+1]; for(int i=1; i <= N; i++) edges[i] = new LinkedList<Integer>(); for(int i=0; i < M; i++) { st = new StringTokenizer(infile.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); edges[a].add(b); edges[b].add(a); } FenwickTree bit = new FenwickTree(M); for(int i=0; i < M; i++) bit.add(i+1, prices[i]); long res = Long.MAX_VALUE; int[] d1 = bfs(A, edges); int[] d2 = bfs(B, edges); int[] d3 = bfs(C, edges); for(int v=1; v <= N; v++) if(d1[v]+d2[v]+d3[v] <= M) res = Math.min(res, bit.find(d2[v])+bit.find(d1[v]+d2[v]+d3[v])); sb.append(res+"\n"); } System.out.print(sb); } public static int[] bfs(int start, LinkedList<Integer>[] edges) { int[] dist = new int[N+1]; Arrays.fill(dist, -1); dist[start] = 0; Queue<Integer> q = new LinkedList<Integer>(); q.add(start); while(q.size() > 0) { int curr = q.poll(); for(int next: edges[curr]) if(dist[next] == -1) { dist[next] = dist[curr]+1; q.add(next); } } return dist; } public static void sort(int[] arr) { //stable heap sort PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for(int a: arr) pq.add(a); for(int i=0; i < arr.length; i++) arr[i] = pq.poll(); } } class FenwickTree { //1 indexed public long[] tree; public int size; public FenwickTree(int size) { this.size = size; tree = new long[size+5]; } public void add(int i, int v) { while(i <= size) { tree[i] += v; i += i&-i; } } public long find(int i) { long res = 0L; while(i >= 1) { res += tree[i]; i -= i&-i; } return res; } public long find(int l, int r) { return find(r)-find(l-1); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
10de94a045ae243145f2dff1329aa9d6
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class E636{ public static void bfs(ArrayList<Integer> adj[],int src,int dist[],int n){ boolean vis[]=new boolean[n+1]; Queue<Integer> q=new LinkedList<Integer>(); vis[src]=true; q.add(src); dist[src]=0; while(!q.isEmpty()){ int v=q.poll(); for(int x:adj[v]){ if(!vis[x]){ vis[x]=true; dist[x]=dist[v]+1; q.add(x); } } } } public static void main(String args[]){ FastReader sc = new FastReader(); StringBuilder sb=new StringBuilder(); int t,i,n,a,b,c,u,v,m; t=sc.nextInt(); while(t-->0){ n=sc.nextInt(); m=sc.nextInt(); a=sc.nextInt(); b=sc.nextInt(); c=sc.nextInt(); long pr[]=new long[m+1]; pr[0]=0; for(i=1;i<=m;i++) pr[i]=sc.nextInt(); Arrays.sort(pr); for(i=2;i<=m;i++) pr[i]=pr[i]+pr[i-1]; ArrayList<Integer> adj[]=new ArrayList[n+1]; for(i=1;i<=n;i++) adj[i]=new ArrayList<Integer>(); for(i=1;i<=m;i++){ u=sc.nextInt(); v=sc.nextInt(); adj[u].add(v); adj[v].add(u); } int dista[]=new int[n+1]; int distb[]=new int[n+1]; int distc[]=new int[n+1]; bfs(adj,a,dista,n); bfs(adj,b,distb,n); bfs(adj,c,distc,n); long min=Long.MAX_VALUE/2; for(i=1;i<=n;i++){ int temp=dista[i]+distb[i]+distc[i]; if(temp>m) continue; long temp2=pr[distb[i]]+pr[temp]; min=Math.min(min,temp2); } sb.append(min).append('\n'); } sb.deleteCharAt(sb.length()-1); out.println(sb); } static PrintWriter out; static class FastReader{ BufferedReader br; StringTokenizer st; public FastReader(){ br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(System.out,true); } 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 boolean isPrime(int n) { if(n<2) return false; for(int i=2;i<=(int)Math.sqrt(n);i++) { if(n%i==0) return false; } return true; } public static void print(int a[],int l,int r){ int i; for(i=l;i<=r;i++) out.print(a[i]+" "); out.println(); } public static long fastexpo(long x, long y, long p){ long res=1; while(y > 0){ if((y & 1)==1) res= ((res%p)*(x%p))%p; y= y >> 1; x = ((x%p)*(x%p))%p; } return res; } public static boolean[] sieve (int n) { boolean primes[]=new boolean[n+1]; Arrays.fill(primes,true); primes[0]=primes[1]=false; for(int i=2;i*i<=n;i++){ if(primes[i]){ for(int j=i*i;j<=n;j+=i) primes[j]=false; } } return primes; } public static long gcd(long a,long b){ return (BigInteger.valueOf(a).gcd(BigInteger.valueOf(b))).longValue(); } public static void merge(int a[],int l,int m,int r){ int n1,n2,i,j,k; n1=m-l+1; n2=r-m; int L[]=new int[n1]; int R[]=new int[n2]; for(i=0;i<n1;i++) L[i]=a[l+i]; for(j=0;j<n2;j++) R[j]=a[m+1+j]; i=0;j=0; k=l; while(i<n1&&j<n2){ if(L[i]<=R[j]){ a[k]=L[i]; i++; } else{ a[k]=R[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=R[j]; j++; k++; } } public static void sort(int a[],int l,int r){ int m; if(l<r){ m=(l+r)/2; sort(a,l,m); sort(a,m+1,r); merge(a,l,m,r); } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
e0bb0d73fc8f92c98e8568420370b168
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); static int MOD = 1000000007; public static void main(String[] args) throws IOException { Main m = new Main(); m.solve(); m.close(); } void close() throws IOException { pw.flush(); pw.close(); br.close(); } int ri() throws IOException { return Integer.parseInt(br.readLine()); } long rl() throws IOException { return Long.parseLong(br.readLine()); } int[] ril(int n) throws IOException { int[] nums = new int[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); int x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } long[] rll(int n) throws IOException { long[] nums = new long[n]; int c = 0; for (int i = 0; i < n; i++) { int sign = 1; c = br.read(); long x = 0; if (c == '-') { sign = -1; c = br.read(); } while (c >= '0' && c <= '9') { x = x * 10 + c - '0'; c = br.read(); } nums[i] = x * sign; } while (c != '\n' && c != -1) c = br.read(); return nums; } void solve() throws IOException { int t = ri(); for (int ti = 0; ti < t; ti++) { int[] nmabc = ril(5); int n = nmabc[0]; int m = nmabc[1]; int a = nmabc[2]-1; int b = nmabc[3]-1; int c = nmabc[4]-1; int[] p = ril(m); Arrays.sort(p); List<List<Integer>> adj = new ArrayList<>(n); for (int i = 0; i < n; i++) adj.add(new ArrayList<>()); for (int i = 0; i < m; i++) { int[] uv = ril(2); adj.get(uv[0]-1).add(uv[1]-1); adj.get(uv[1]-1).add(uv[0]-1); } long[] prefix = new long[m]; prefix[0] = p[0]; for (int i = 1; i < m; i++) { prefix[i] = prefix[i-1] + p[i]; } int[] distFromA = bfs(adj, a); int[] distFromB = bfs(adj, b); int[] distFromC = bfs(adj, c); long best = Long.MAX_VALUE; for (int i = 0; i < n; i++) { int overlap = distFromB[i]; int notoverlap = distFromA[i] + distFromC[i]; if (overlap + notoverlap - 1 >= prefix.length) continue; long overlapcost = (overlap-1 >= 0 ? prefix[overlap-1] : 0) * 2; long notoverlapcost = overlap+notoverlap-1 >= 0 ? prefix[overlap+notoverlap-1] - overlapcost / 2 : 0; long cost = overlapcost + notoverlapcost; best = Math.min(best, cost); } pw.println(best); } } int[] bfs(List<List<Integer>> adj, int r) { int n = adj.size(); boolean[] visited = new boolean[n]; int[] dist = new int[n]; Deque<Integer> q = new ArrayDeque<>(); q.addLast(r); visited[r] = true; dist[r] = 0; while (!q.isEmpty()) { int u = q.removeFirst(); for (int v : adj.get(u)) { if (!visited[v]) { visited[v] = true; dist[v] = dist[u] + 1; q.addLast(v); } } } return dist; } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
4535ad5bcb899837385c4be4255edacd
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class A { //Solution by Sathvik Kuthuru public static void main(String[] args) { FastReader scan = new FastReader(); PrintWriter out = new PrintWriter(System.out); Task solver = new Task(); int t = scan.nextInt(); for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out); out.close(); } static class Task { int n, m, a, b, c; ArrayList<Integer>[] adj; public void solve(int testNumber, FastReader scan, PrintWriter out) { n = scan.nextInt(); m = scan.nextInt(); a = scan.nextInt() - 1; b = scan.nextInt() - 1; c = scan.nextInt() - 1; adj = new ArrayList[n]; int[] distA = new int[n], distB = new int[n], distC = new int[n]; long[] cost = new long[m]; for(int i = 0; i < n; i++) { adj[i] = new ArrayList<>(); distA[i] = distB[i] = distC[i] = Integer.MAX_VALUE; } for(int i = 0; i < m; i++) cost[i] = scan.nextInt(); for(int i = 0; i < m; i++) { int a = scan.nextInt() - 1, b = scan.nextInt() - 1; adj[a].add(b); adj[b].add(a); } shuffle(cost); Arrays.sort(cost); for(int i = 1; i < m; i++) cost[i] += cost[i - 1]; bfs(distA, a); bfs(distB, b); bfs(distC, c); long ans = Long.MAX_VALUE; for(int i = 0; i < n; i++) { int common = distB[i], other = distA[i] + distC[i], next = common + other - 1; if(common + other > m) continue; long curr = common == 0 ? 0 : cost[common - 1]; curr *= 2; curr += next < 0 ? 0 : common == 0 ? cost[next] : cost[next] - cost[common - 1]; ans = Math.min(ans, curr); } out.println(ans); } void bfs(int[] dist, int start) { ArrayDeque<Integer> queue = new ArrayDeque<>(); dist[start] = 0; queue.addLast(start); while(!queue.isEmpty()) { int q = queue.pollFirst(); for(int i : adj[q]) { if(dist[q] + 1 < dist[i]) { dist[i] = dist[q] + 1; queue.addLast(i); } } } } } static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } static void shuffle(long[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); long temp = a[i]; a[i] = a[r]; a[r] = temp; } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public FastReader(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } 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\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
bd183b936fc87964635661ed131b5bc9
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
// Working program with FastReader import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Problem5 { 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 s=new FastReader(); int t = s.nextInt(); for(int i=0;i<t;i++){ int n = s.nextInt(); int m = s.nextInt(); int a = s.nextInt(); int b = s.nextInt(); int c = s.nextInt(); int[] weigths = new int[m]; ArrayList<Integer>[] adjL = new ArrayList[n]; for(int j=0;j<n;j++){ adjL[j] = new ArrayList<Integer>(); } for(int j=0;j<m;j++){ weigths[j] = s.nextInt(); } Arrays.sort(weigths); for(int k =0;k<m;k++){ int e1 = s.nextInt(); int e2 = s.nextInt(); adjL[e1-1].add(e2-1); adjL[e2-1].add(e1-1); } System.out.println(weightdist(n,m,a,b,c,weigths,adjL)); } } public static long weightdist(int n,int m,int a,int b,int c,int[] weigths,ArrayList<Integer>[] adjL){ int[] dista = new int[n]; int[] distb = new int[n]; int[] distc = new int[n]; dista = bfs(a-1,n,adjL); distb = bfs(b-1,n,adjL); distc =bfs(c-1,n,adjL); long[] pref = new long[m+1]; pref[0] = 0l; // System.out.println(dista[n-1]+" "+distb[n-1]+" "+distc[n-1]); for(int i=0;i<m;i++){ pref[i+1] = weigths[i]+pref[i]; } long min = Long.MAX_VALUE; for(int i=0;i<n;i++){ if(dista[i]+distb[i]+distc[i]>m){ continue; } long temp = pref[distb[i]] + pref[dista[i]+distb[i]+distc[i]]; if(temp<min){ min = temp; } } return min; } public static int[] bfs(int index,int n, ArrayList<Integer>[] adjL){ int[] dist = new int[n]; int inf = Integer.MAX_VALUE; Arrays.fill(dist,inf); Queue<Integer> q = new LinkedList<Integer>(); q.add(index); dist[index] =0; while(!q.isEmpty()){ int head = q.remove(); int size = adjL[head].size(); for(int i=0;i<size;i++){ int neigh = adjL[head].get(i); if(dist[neigh]==inf){ dist[neigh] = dist[head]+1; q.add(neigh); } } } return dist; } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
ed173fcc22d0d4079b5d97b3296c4ee4
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { static class Pair implements Comparable<Pair>{ int a; int b; public Pair(int x,int y){a=Math.min(x, y);b=Math.max(x, y);} public Pair(){} public int compareTo(Pair p){ return p.a - a; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + a; result = prime * result + b; // out.println("hashcode = "+result); return result; } @Override public boolean equals(Object obj) { Pair cur = (Pair)obj; if((a==cur.a && b==cur.b) || (a==cur.b && b==cur.a))return true; return false; } } static class cell implements Comparable<cell>{ int a,b; long dis; public cell(int x,int y,long z) {a=x;b=y;dis=z;} public int compareTo(cell c) { return Long.compare(dis,c.dis); } } static class TrieNode{ TrieNode[]child; int w; boolean term; TrieNode(){ child = new TrieNode[26]; } } public static long gcd(long a,long b) { if(a<b) return gcd(b,a); if(b==0) return a; return gcd(b,a%b); } static long lcm(long a,long b) { return a*b / gcd(a,b); } //static long ans = 0; static long mod = (long)(1e9+7);///998244353; public static void main(String[] args) throws Exception { new Thread(null, null, "Anshum Gupta", 99999999) { public void run() { try { solve(); } catch(Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static long pow(long x,long y){ if(y == 0)return 1; if(y==1)return x; long a = pow(x,y/2); a = (a*a)%mod; if(y%2==0){ return a; } return (a*x)%mod; } static long mxx; static int mxN = (int)(3e5+5); static long[]fact,inv_fact; static long my_inv(long a) { return pow(a,mod-2); } static long bin(int a,int b) { if(a < b || a<0 || b<0)return 0; return ((fact[a]*inv_fact[a-b])%mod * inv_fact[b])%mod; } static ArrayList<ArrayList<Integer>>adj; static boolean[]vis; static Long[]p; static long val; static int[]bfs(int a){ Queue<Integer> q = new LinkedList<Integer>(); vis = new boolean[n+1]; int[]dis = new int[n+1]; q.add(a); dis[a] = 0; vis[a] = true; while(!q.isEmpty()) { int cur = q.poll(); // vis[cur] = true; // if(cur == b)break; for(int x : adj.get(cur)) { if(vis[x])continue; q.add(x); dis[x] = dis[cur]+1; vis[x] = true; } } return dis; } static int n,m; public static void solve() throws Exception { // solve the problem here MyScanner s = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out), true); int tc = s.nextInt(); mxx = (long)(1e18+5); // fact=new long[mxN]; // inv_fact = new long[mxN]; // fact[0]=inv_fact[0]=1L; // for(int i=1;i<mxN;i++) { // fact[i] = (i*fact[i-1])%mod; // inv_fact[i] = my_inv(fact[i]); // } while(tc-->0){ n = s.nextInt(); m = s.nextInt(); int a = s.nextInt(); int b = s.nextInt(); int c = s.nextInt(); p = new Long[m+1]; p[0]=0L; Pair[]edges = new Pair[m+1]; adj = new ArrayList<ArrayList<Integer>>(); for(int i=1;i<=m;i++) { p[i]=s.nextLong(); } Arrays.parallelSort(p); long[]pre=new long[m+1]; for(int i=1;i<=m;i++) { pre[i] = pre[i-1]+p[i]; } for(int i=0;i<=n;i++)adj.add(new ArrayList<Integer>()); for(int i=1;i<=m;i++) { int u = s.nextInt(); int v = s.nextInt(); adj.get(u).add(v); adj.get(v).add(u); edges[i] = new Pair(u,v); } int[]da = bfs(a); int[]db = bfs(b); int[]dc = bfs(c); long ans = mxx; for(int i=1;i<=n;i++) { if(da[i] + db[i] + dc[i] > m)continue; ans = Math.min(ans, pre[db[i]] + pre[db[i]+da[i]+dc[i]]); } out.println(ans); // } out.flush(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } //-------------------------------------------------------- }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
4124f5f637a2ce6269e8041c440f2774
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.util.*; public class Main { static PrintWriter out = new PrintWriter(System.out); static Scanner sc = new Scanner(System.in); static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); long mod = 998244353; long inv2 =1; int step = 1; long[] ans; Map<Integer, Long>[] ope; int maxn = 2*100000; List<Integer>[] tree = new List[maxn+1]; int[] da, db, dc; public static void main(String[] args) throws IOException { Main main = new Main(); int t = main.paIn(reader.readLine()); while(t-->0){ main.solve(); } // main.solve(); // long ans = main.solve(); out.flush(); } void solve() throws IOException { String[] buf = reader.readLine().split(" "); int n = paIn(buf[0]), m = paIn(buf[1]), a = paIn(buf[2]), b = paIn(buf[3]), c = paIn(buf[4]); for(int i=1; i<=n ;i++) tree[i] = new LinkedList<>(); long[] p = new long[m+1]; buf = reader.readLine().split(" "); for(int i=1; i<=m; i++) p[i] = paIn(buf[i-1]); Arrays.sort(p); long[] sum = new long[m+1]; for(int i=1; i<=m; i++) sum[i] = sum[i-1]+p[i]; for(int i=0; i<m; i++){ buf = reader.readLine().split(" "); int u = paIn(buf[0]), v = paIn(buf[1]); tree[u].add(v); tree[v].add(u); } da = new int[n+1]; db = new int[n+1]; dc = new int[n+1]; bfs(a,da); bfs(b,db); bfs(c, dc); long ans = Long.MAX_VALUE/2; for(int mid = 1; mid<=n; mid++){ int ma = da[mid], mb = db[mid], mc = dc[mid]; if(ma+mc+mb>m) continue; // definitely impossible long cur = sum[ma+mb+mc]+sum[mb]; ans = Math.min(ans, cur); } out.println(ans); } void bfs(int start, int[] dist){ Arrays.fill(dist, maxn+10); dist[start] = 0; int step = 1; List<Integer> cur = new LinkedList<>(), next = new LinkedList<>(); cur.add(start); while(cur.size()>0){ for(int now:cur){ for(int to:tree[now]){ if(dist[to]>step){ dist[to] = step; next.add(to); } } } cur = next; next = new LinkedList<>(); step++; } } int paIn(String s){return Integer.parseInt(s);} }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
450e3c658ca5dc47ac6c219989b7af3f
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
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.Collection; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Queue; import java.util.LinkedList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Van Hanh Pham <skyvn97> <vanhanh.pham@gmail.com> */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskE solver = new TaskE(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskE { private ArrayList<Integer>[] adj; int numNode; public void solve(int testNumber, InputReader in, PrintWriter out) { numNode = in.nextInt(); int numEdge = in.nextInt(); int start = in.nextInt(); int mid = in.nextInt(); int end = in.nextInt(); int[] weights = IOUtils.readIntArray(in, numEdge, 1); Arrays.sort(weights, 1, numEdge + 1); long[] sumWeight = new long[numEdge + 1]; sumWeight[0] = 0; for (int i = 1; i <= numEdge; i++) sumWeight[i] = sumWeight[i - 1] + weights[i]; adj = new ArrayList[numNode + 1]; for (int i = 1; i <= numNode; i++) adj[i] = new ArrayList<Integer>(); for (int i = 0; i < numEdge; i++) { int u = in.nextInt(); int v = in.nextInt(); adj[u].add(v); adj[v].add(u); } int[] distStart = bfs(start); int[] distMid = bfs(mid); int[] distEnd = bfs(end); long result = Others.LONG_INFINITY; for (int i = 1; i <= numNode; i++) { int once = distStart[i] + distEnd[i]; int twice = distMid[i]; if (once + twice > numEdge) continue; result = Math.min(result, sumWeight[once + twice] + sumWeight[twice]); } out.println(result); } private int[] bfs(int start) { int[] dist = new int[numNode + 1]; Arrays.fill(dist, -1); Queue<Integer> queue = new LinkedList<Integer>(); dist[start] = 0; queue.add(start); while (!queue.isEmpty()) { int u = queue.remove(); for (int v : adj[u]) if (dist[v] < 0) { dist[v] = dist[u] + 1; queue.add(v); } } return dist; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String nextString() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String next() { return nextString(); } public int nextInt() { return Integer.parseInt(nextString()); } } static class Others { public static final long LONG_INFINITY = (long) 1e18 + 7; } static class IOUtils { public static int[] readIntArray(InputReader in, int size, int start) { int[] res = new int[start + size]; for (int i = start; i < start + size; i++) res[i] = in.nextInt(); return res; } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
55b23dc75ef0ead20dd65b5b28f005fb
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.*; public class Main { InputStream is; PrintWriter out; String INPUT = ""; //class Declaration static class pair implements Comparable<pair>{ int x; int y; pair (int i,int j) { x=i; y=j; } public int compareTo(pair p){ if(this.x!=p.x) { return this.x-p.x;} else { return this.y-p.y;} } public int hashCode() { return (x+" "+y).hashCode();} public String toString(){ return x+" "+y;} public boolean equals(Object o){ pair x = (pair) o ; return (x.x==this.x&&x.y==this.y);} } long mod = (long)1e9 + 7 ; ArrayList<ArrayList<Integer>> g ; int [] da,db,dc ; int n,m,a,b,c; void solve() throws Exception{ int t=ni(); while(t-->0){ n=ni();m=ni(); a=ni() ; b=ni(); c=ni(); //print("val of n "+n); g = new ArrayList<>(); da= new int[n+1]; db= new int[n+1]; dc= new int[n+1]; for(int i=0;i<=n;++i) g.add(new ArrayList<>()); Long[] costs = new Long[m]; for(int i=0;i<m;++i) costs[i]=nl(); for(int i=0;i<m;++i){ int x=ni(),y=ni(); g.get(x).add(y); g.get(y).add(x); } Arrays.sort(costs); long prefix[] = new long[m+1]; for(int i=1;i<=m;++i) prefix[i] = prefix[i-1] + costs[i-1]; bfs(a,da); bfs(b,db); bfs(c,dc); long ans = Long.MAX_VALUE ; //pn("da : "+Arrays.toString(da)); //pn("db : "+Arrays.toString(db)); //pn("dc : "+Arrays.toString(dc)); int xx= 0; for(int x=1;x<=n;++x){ long la = Long.MAX_VALUE; if(da[x]+db[x]+dc[x] <= m) la =prefix[da[x]+db[x]+dc[x]] + prefix[db[x]] ; //ans = Math.min(prefix[(int)Math.min(da[x]+db[x]+dc[x],m)] + prefix[db[x]], ans ); if(la < ans ){ xx = x ; ans = la ; } } //pn("xx : "+ xx); pn(ans); } } void bfs(int s,int[] d){ LinkedList<Integer> q = new LinkedList<>(); int[] par = new int[n+1]; boolean[] vis = new boolean[n+1]; par[s] = s ; d[s] = -1 ; q.add(s); while(!q.isEmpty()){ int ver = q.pollFirst(); if(vis[ver]) continue ; vis[ver] = true ; d[ver] = d[par[ver]] + 1 ; for(int x : g.get(ver)){ if(vis[x] || par[x]!=0){ continue ; } par[x]= ver; q.add(x); } } } long pow(long a,long b){ long result = 1; while(b>0){ if(b%2==1) result = (result * a) % mod; b/=2; a=(a*a)%mod; } return result; } void print(Object o){ System.out.println(o); System.out.flush(); } int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } void run() throws Exception{ is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new Main().run(); } //output methods private void pn(Object o) { out.println(o); } private void p(Object o) { out.print(o); } //input methods private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private void tr(Object... o) { if(INPUT.length() > 0)System.out.println(Arrays.deepToString(o)); } void watch(Object ... a) throws Exception{ int i=1; pn("watch starts :"); for(Object o : a ) { //print(o); boolean notfound = true; if(o.getClass().isArray()){ String type = o.getClass().getName().toString(); print("type is "+type); switch (type) { case "[I":{ int[] test = (int[])o ; pn(i+" "+Arrays.toString(test)); break; } case "[[I":{ int[][] obj = (int[][])o; pn(i+" "+Arrays.deepToString(obj)); break; } case "[J" : { long[] obj = (long[])o ; pn(i+" "+Arrays.toString(obj)); break; } case "[[J": { long[][] obj = (long[][])o; pn(i+" "+Arrays.deepToString(obj)); break; } case "[D" :{ double[] obj= (double[])o; pn(i+" "+Arrays.toString(obj)); break; } case "[[D" :{ double[][] obj = (double[][])o; pn(i+" "+Arrays.deepToString(obj)); break; } case "[Ljava.lang.String": { String[] obj = (String[])o ; pn(i+" "+Arrays.toString(obj)); break; } case "[[Ljava.lang.String": { String[][] obj = (String[][])o ; pn(i+" "+Arrays.deepToString(obj)); break ; } case "[C" :{ char[] obj = (char[])o ; pn(i+" "+Arrays.toString(obj)); break; } case "[[C" :{ char[][] obj = (char[][])o; pn(i+" "+Arrays.deepToString(obj)); break; } default:{ pn(i+" type not identified"); break; } } notfound = false; } if(o.getClass() == ArrayList.class){ pn(i+" al: "+o); notfound = false; } if(o.getClass() == HashSet.class){ pn(i+" hs: "+o); notfound = false; } if(o.getClass() == TreeSet.class){ pn(i+" ts: "+o); notfound = false; } if(o.getClass() == TreeMap.class){ pn(i+" tm: "+o); notfound = false; } if(o.getClass() == HashMap.class){ pn(i+" hm: "+o); notfound = false; } if(o.getClass() == LinkedList.class){ pn(i+" ll: "+o); notfound = false; } if(o.getClass() == PriorityQueue.class){ pn(i+" pq : "+o); notfound = false; } if(o.getClass() == pair.class){ pn(i+" pq : "+o); notfound = false; } if(notfound){ pn(i+" unknown: "+o); } i++; } pn("watch ends "); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
2158cfdeb12174f644f10d48045d8a4a
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class A { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static FastReader scn = new FastReader(); public static void main(String[] args) { // int t = 1; int t = scn.nextInt(); while(t-- > 0) run(); } private static HashMap<Integer,HashSet<Integer>> graph; private static void run(){ int n = scn.nextInt(); int m = scn.nextInt(); int a = scn.nextInt(); int b = scn.nextInt(); int c = scn.nextInt(); long[] prices = new long[m+1]; for(int i = 1; i<=m; i++) prices[i] = scn.nextInt(); graph = new HashMap<>(); for(int i = 0; i<m; i++){ int u = scn.nextInt(); int v = scn.nextInt(); if(!graph.containsKey(u)) graph.put(u,new HashSet<>()); if(!graph.containsKey(v)) graph.put(v,new HashSet<>()); graph.get(u).add(v); graph.get(v).add(u); } int[] Adist = bfs(n,a); int[] Bdist = bfs(n,b); int[] Cdist = bfs(n,c); Arrays.sort(prices); for(int i = 2; i<=m; i++) prices[i] += prices[i-1]; long min = Long.MAX_VALUE; for(int i = 1; i<=n; i++){ int dd = Adist[i] + Bdist[i] + Cdist[i]; if(dd>m) continue; long temp = prices[Bdist[i]] + prices[dd]; min = Math.min(temp,min); } System.out.println(min); } private static int[] bfs(int n, int start){ LinkedList<Integer> queue = new LinkedList<>(); HashSet<Integer> visited = new HashSet<>(); queue.add(start); queue.addLast(-1); int[] res = new int[n+1]; int dist = 1; while(!queue.isEmpty()){ int current = queue.removeFirst(); if(current == -1){ dist++; if(!queue.isEmpty()) queue.addLast(-1); continue; } if(visited.contains(current)) continue; visited.add(current); for(int neigh : graph.get(current)){ if(!visited.contains(neigh)){ if(res[neigh] == 0) res[neigh] = dist; queue.addLast(neigh); } } } return res; } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
1db60fa4ab7cd81d37b512484ad73977
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.InputMismatchException; import java.util.List; public class Main { InputStream is; PrintWriter out; String INPUT = ""; private static final long M = 1000000007; boolean[] vis; List<Integer>[] g; void solve() { int T = ni(); while (T-- > 0) { int N = ni(); int M = ni(); int A = ni() - 1; int B = ni() - 1; int C = ni() - 1; int[] w = na(M); Arrays.sort(w); long pre[] = new long[M + 1]; for (int i = 0; i < M; i++) pre[i + 1] = pre[i] + w[i]; g = new List[N]; for (int i = 0; i < N; i++) g[i] = new ArrayList<Integer>(); for (int i = 0; i < M; i++) { int u = ni() - 1; int v = ni() - 1; g[u].add(v); g[v].add(u); } int d[][] = new int[3][N]; bfs(A, d[0]); bfs(B, d[1]); bfs(C, d[2]); for (int i = 0; i < N; i++) g[i] = new ArrayList<Integer>(); long ans = Long.MAX_VALUE; for (int i = 0; i < N; i++) { if (d[1][i] + d[0][i] + d[2][i] <= M) ans = Math.min(ans, pre[d[1][i]] + pre[d[1][i] + d[0][i] + d[2][i]]); } out.println(ans); } } private void bfs(int u, int[] d) { Arrays.fill(d, -1); int depth = 0; ArrayDeque<Integer> q = new ArrayDeque<Integer>(); q.add(u); d[u] = depth++; while (!q.isEmpty()) { int sz = q.size(); for (int i = 0; i < sz; i++) { Integer v = q.poll(); for (Integer w : g[v]) { if (d[w] == -1) { d[w] = depth; q.add(w); } } } depth++; } } long power(long a, long b) { long x = 1, y = a; while (b > 0) { if (b % 2 != 0) { x = (x * y) % M; } y = (y * y) % M; b /= 2; } return x % M; } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms"); } public static void main(String[] args) throws Exception { new Main().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if (lenbuf == -1) throw new InputMismatchException(); if (ptrbuf >= lenbuf) { ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if (lenbuf <= 0) return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char) skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' // ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while (p < n) { if (!(isSpaceChar(b))) buf[p++] = (char) b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = ni(); return a; } private int[][] na(int n, int m) { int[][] a = new int[n][]; for (int i = 0; i < n; i++) a[i] = na(m); return a; } private int ni() { int num = 0, b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ; if (b == '-') { minus = true; b = readByte(); } while (true) { if (b >= '0' && b <= '9') { num = num * 10 + (b - '0'); } else { return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
e67e6e5c1b02560ff6847a0ab3ff53a4
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ for(int q=ni();q>0;q--) { work(); } out.flush(); } long mod=998244353L; long inf=Long.MAX_VALUE; long gcd(long a,long b) { return a==0?b:gcd(b%a,a); } ArrayList<Integer>[] graph; void work() { int n=ni(),m=ni(),a=ni()-1,b=ni()-1,c=ni()-1; long[] W=na(m); Arrays.sort(W); graph=ng(n,m); long ret=Long.MAX_VALUE; int[] d1=new int[n]; int[] d2=new int[n]; int[] d3=new int[n]; find(a,d1); find(b,d2); find(c,d3); long[] sum=new long[m]; for(int i=0;i<m;i++) { sum[i]=(i==0?0:sum[i-1])+W[i]; } for(int i=0;i<n;i++) { int s1=d1[i]; int s2=d2[i]; int s3=d3[i]; int s=s1+s2+s3; if(s<=m) { ret=Math.min(ret, (s==0?0:sum[s1+s2+s3-1])+(s2==0?0:sum[s2-1])); } } out.println(ret); } private void find(int root, int[] d) { LinkedList<Integer> queue=new LinkedList<>(); boolean[] vis=new boolean[d.length]; vis[root]=true; queue.add(root); int dis=0; while(queue.size()>0) { int len=queue.size(); dis++; while(len-->0) { int node=queue.poll(); for(int nn:graph[node]) { if(!vis[nn]) { vis[nn]=true; d[nn]=dis; queue.add(nn); } } } } } //input @SuppressWarnings("unused") private ArrayList<Integer>[] ng(int n, int m) { ArrayList<Integer>[] graph=(ArrayList<Integer>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { int s=in.nextInt()-1,e=in.nextInt()-1; graph[s].add(e); graph[e].add(s); } return graph; } private ArrayList<long[]>[] ngw(int n, int m) { ArrayList<long[]>[] graph=(ArrayList<long[]>[])new ArrayList[n]; for(int i=0;i<n;i++) { graph[i]=new ArrayList<>(); } for(int i=1;i<=m;i++) { long s=in.nextLong()-1,e=in.nextLong()-1,w=in.nextLong(); graph[(int)s].add(new long[] {e,w,i}); graph[(int)e].add(new long[] {s,w}); } return graph; } private int ni() { return in.nextInt(); } private long nl() { return in.nextLong(); } private String ns() { return in.next(); } private long[] na(int n) { long[] A=new long[n]; for(int i=0;i<n;i++) { A[i]=in.nextLong(); } return A; } private int[] nia(int n) { int[] A=new int[n]; for(int i=0;i<n;i++) { A[i]=in.nextInt(); } return A; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { while(st==null || !st.hasMoreElements())//回车,空行情况 { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
d3c84d72b9c689ac2b06a683f8252525
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class Solution implements Runnable { static class pair implements Comparable { int f; int s; pair(int fi, int se) { f=fi; s=se; } public int compareTo(Object o)//desc order { pair pr=(pair)o; if(s>pr.s) return -1; if(s==pr.s) { if(f>pr.f) return 1; else return -1; } else return 1; } public boolean equals(Object o) { pair ob=(pair)o; if(o!=null) { if((ob.f==this.f)&&(ob.s==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f; int s; long t; triplet(int f,int s,long t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; if(o!=null) { if((ob.f==this.f)&&(ob.s==this.s)&&(ob.t==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o)//asc order { triplet tr=(triplet)o; if(t>tr.t) return 1; else return -1; } } void merge1(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int [n1]; int R[] = new int [n2]; for (int i=0; i<n1; ++i) L[i] = arr[l + i]; for (int j=0; j<n2; ++j) R[j] = arr[m + 1+ j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i]<=R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } void sort1(int arr[], int l, int r) { if (l < r) { int m = (l+r)/2; sort1(arr, l, m); sort1(arr , m+1, r); merge1(arr, l, m, r); } } public static void main(String args[])throws Exception { new Thread(null,new Solution(),"Solution",1<<27).start(); } ArrayList<Integer>g[]; void calcdist(int dist[],int n,int src) { int vis[]=new int[n+1]; Queue<Integer>q=new LinkedList<>(); q.add(src); vis[src]=1; while(!q.isEmpty()) { int u=q.remove(); for(int v : g[u]) { if(vis[v]==1) continue; vis[v]=1; q.add(v); dist[v]=dist[u]+1; } } } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int t=in.ni(); while(t--!=0) { int n=in.ni(); int m=in.ni(); int a=in.ni(); int b=in.ni(); int c=in.ni(); int p[]=new int[m+1]; for(int i=1;i<=m;i++) p[i]=in.ni(); sort1(p,1,m); long prefsum[]=new long[m+1]; for(int i=1;i<=m;i++) prefsum[i]=p[i]+prefsum[i-1]; int dist1[]=new int[n+1]; int dist2[]=new int[n+1]; int dist3[]=new int[n+1]; g=new ArrayList[n+1]; for(int i=1;i<=n;i++) g[i]=new ArrayList<>(); for(int i=1;i<=m;i++) { int u=in.ni(); int v=in.ni(); g[u].add(v); g[v].add(u); } calcdist(dist1,n,a); calcdist(dist2,n,b); calcdist(dist3,n,c); long ans=(long)1000000000*100000000; for(int i=1;i<=n;i++) { if(dist1[i]+dist2[i]+dist3[i]>m) continue; long x=2*prefsum[dist2[i]] + prefsum[dist1[i]+dist2[i]+dist3[i]] - prefsum[dist2[i]]; ans=Math.min(ans,x); } out.println(ans); } out.close(); } catch(Exception e){ System.out.println(e); //throw new RuntimeException(); } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(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 ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
a690edb379eeae199041724de4d8ed15
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.text.*; import java.util.*; import java.math.*; public class template { public static void main(String[] args) throws Exception { new template().run(); } public void run() throws Exception { FastScanner f = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int asdf = f.nextInt(); while(asdf-->0) { int n = f.nextInt(), m = f.nextInt(); int a = f.nextInt()-1, b = f.nextInt()-1, c = f.nextInt()-1; Long[] arr = new Long[m]; for(int i = 0; i < m; i++) arr[i] = f.nextLong(); Arrays.sort(arr); long[] psum = new long[m+1]; for(int i = 0; i < m; i++) psum[i+1] = psum[i]+arr[i]; LinkedList<Integer>[] adj = new LinkedList[n]; int[][] dist = new int[n][3]; for(int i = 0; i < n; i++) { adj[i] = new LinkedList<>(); dist[i][0] = dist[i][1] = dist[i][2] = 2147483647; } for(int i = 0; i < m; i++) { int p = f.nextInt()-1; int q = f.nextInt()-1; adj[p].add(q); adj[q].add(p); } LinkedList<Integer> q = new LinkedList<>(); { dist[a][0] = 0; q.add(a); while(!q.isEmpty()) { int i = q.poll(); for(int j : adj[i]) if(dist[j][0] == 2147483647) { dist[j][0] = dist[i][0]+1; q.add(j); } } } { dist[b][1] = 0; q.add(b); while(!q.isEmpty()) { int i = q.poll(); for(int j : adj[i]) if(dist[j][1] == 2147483647) { dist[j][1] = dist[i][1]+1; q.add(j); } } } { dist[c][2] = 0; q.add(c); while(!q.isEmpty()) { int i = q.poll(); for(int j : adj[i]) if(dist[j][2] == 2147483647) { dist[j][2] = dist[i][2]+1; q.add(j); } } } long bestans = Long.MAX_VALUE; for(int i = 0; i < n; i++) if(dist[i][0]+dist[i][1]+dist[i][2] <= m) bestans = Math.min(psum[dist[i][0]+dist[i][1]+dist[i][2]]+psum[dist[i][1]], bestans); out.println(bestans); } out.flush(); } static class FastScanner { public BufferedReader reader; public StringTokenizer tokenizer; public FastScanner() { reader = new BufferedReader(new InputStreamReader(System.in), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public 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 reader.readLine(); } catch(IOException e) { throw new RuntimeException(e); } } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
c50dda727c18661ebe079589e409b0cc
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.nio.CharBuffer; import java.util.*; public class P1343E { public static void main(String[] args) { SimpleScanner scanner = new SimpleScanner(System.in); PrintWriter writer = new PrintWriter(System.out); int caseNum = scanner.nextInt(); while (caseNum-- > 0) { int n = scanner.nextInt(); int m = scanner.nextInt(); int a = scanner.nextInt() - 1; int b = scanner.nextInt() - 1; int c = scanner.nextInt() - 1; List<Integer> p = new ArrayList<>(m); for (int i = 0; i < m; ++i) p.add(scanner.nextInt()); p.sort(Comparator.naturalOrder()); long[] prefix = new long[m + 1]; for (int i = 1; i <= m; ++i) prefix[i] = prefix[i - 1] + p.get(i - 1); List<List<Integer>> links = new ArrayList<>(); for (int i = 0; i < n; ++i) links.add(new LinkedList<>()); for (int i = 0; i < m; ++i) { int u = scanner.nextInt() - 1; int v = scanner.nextInt() - 1; links.get(u).add(v); links.get(v).add(u); } int[] da = new int[n]; int[] db = new int[n]; int[] dc = new int[n]; bfs(links, a, da); bfs(links, b, db); bfs(links, c, dc); long ans = Long.MAX_VALUE; for (int i = 0; i < n; ++i) if (da[i] + db[i] + dc[i] <= m) ans = Math.min(ans, prefix[db[i]] + prefix[da[i] + db[i] + dc[i]]); writer.println(ans); } writer.close(); } private static void bfs(List<List<Integer>> links, int root, int[] d) { Arrays.fill(d, -1); d[root] = 0; LinkedList<Integer> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int u = queue.poll(); for (int v : links.get(u)) { if (d[v] < 0) { d[v] = d[u] + 1; queue.offer(v); } } } } private static class SimpleScanner { private static final int BUFFER_SIZE = 10240; private Readable in; private CharBuffer buffer; private boolean eof; private SimpleScanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); buffer = CharBuffer.allocate(BUFFER_SIZE); buffer.limit(0); eof = false; } private char read() { if (!buffer.hasRemaining()) { buffer.clear(); int n; try { n = in.read(buffer); } catch (IOException e) { n = -1; } if (n <= 0) { eof = true; return '\0'; } buffer.flip(); } return buffer.get(); } private void checkEof() { if (eof) throw new NoSuchElementException(); } private char nextChar() { checkEof(); char b = read(); checkEof(); return b; } private String next() { char b; do { b = read(); checkEof(); } while (Character.isWhitespace(b)); StringBuilder sb = new StringBuilder(); do { sb.append(b); b = read(); } while (!eof && !Character.isWhitespace(b)); return sb.toString(); } private int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private double nextDouble() { return Double.parseDouble(next()); } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
d3bea457ebba46fac876b102cc913ab3
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class e_636 { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub FastScanner in = new FastScanner(System.in); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); int T = in.nextInt(); for(int aa = 0; aa < T; aa++) { solve(in, out); } out.close(); } static ArrayList<Integer> [] adj; static void solve(FastScanner in, PrintWriter out) throws Exception { int N = in.nextInt(); int M = in.nextInt(); adj = new ArrayList[N]; int A = in.nextInt()-1; int B = in.nextInt()-1; int C = in.nextInt()-1; for(int i = 0; i < N; i++) { adj[i] = new ArrayList<Integer>(); } int p [] = new int [M]; for(int i = 0; i < M; i++) { p[i] = in.nextInt(); } for(int i = 0; i < M; i++) { int u = in.nextInt()-1; int v = in.nextInt()-1; adj[u].add(v); adj[v].add(u); } int a [] = new int [N]; int b [] = new int [N]; int c [] = new int [N]; fill(a); fill(b); fill(c); bfs(a, A); bfs(b, B); bfs(c, C); Arrays.sort(p); long psum [] = new long [M+1]; for(int i = 0; i < M; i++) { psum[i+1] = psum[i] + p[i]; } long min = Long.MAX_VALUE/2; for(int i = 0; i < N; i++) { int bsum = b[i]; int tsum = a[i] + b[i] + c[i]; if(tsum <= M) { // System.out.println(bsum+" "+tsum); min = Math.min(min, psum[bsum] + psum[tsum]); } } out.println(min); } static void bfs(int dis [], int node) { Queue<int []> q = new LinkedList<>(); q.add(new int [] {node, 0}); while(!q.isEmpty()) { int next [] = q.poll(); int pos = next[0]; int d = next[1]; dis[pos] = d; // System.out.println(pos+" "+d+" "+node+" !"); for(int edge : adj[pos]) { if(dis[edge] == -1) { dis[edge] = d+1; q.add(new int [] {edge, d+1}); } } } } static void fill(int a []) { for(int i = 0; i < a.length; i++) { a[i] = -1; } } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); st = new StringTokenizer(""); } public FastScanner(String fileName) throws Exception { br = new BufferedReader(new FileReader(new File(fileName))); st = new StringTokenizer(""); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public Double nextDouble() throws Exception { return Double.parseDouble(next()); } public String nextLine() throws Exception { if (st.hasMoreTokens()) { StringBuilder str = new StringBuilder(); boolean first = true; while (st.hasMoreTokens()) { if (first) { first = false; } else { str.append(" "); } str.append(st.nextToken()); } return str.toString(); } else { return br.readLine(); } } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
507d084edd4821c8086dc87ac4e7447d
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.*; import java.nio.charset.Charset; import java.util.*; public class run { public static void main(String args[]) throws IOException { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int tc = in.nextInt(); while ((tc--) > 0) { int n = in.nextInt(); int m = in.nextInt(); int a = in.nextInt(); int b = in.nextInt(); int c = in.nextInt(); long[] weight = new long[m+1]; weight[0] = 0; for(int i = 1; i <= m; i++) { weight[i] = in.nextLong(); } ArrayList<Integer>[] g = new ArrayList[n + 1]; for (int i = 0; i <= n; i++) { g[i] = new ArrayList<Integer>(); } for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); g[x].add(y); g[y].add(x); } int[] da = solve(g, a, n); int[] db = solve(g, b, n); int[] dc = solve(g, c, n); Arrays.sort(weight); for(int i = 1; i <= m ; i++){ weight[i] += weight[i-1]; } long ans = Long.MAX_VALUE; for(int i = 1; i <= n ; i++) { int com = db[i]; long temp = weight[com] * 2; int rem = da[i] + dc[i] + com; if(rem > m) continue; temp += weight[rem] - weight[com]; ans = Long.min(ans,temp); } pw.println(ans); } pw.flush(); pw.close(); } private static int[] solve(ArrayList<Integer>[] g, int a, int n) { int dist[] = new int[n+1]; for (int i = 0; i < n + 1; i++) { dist[i] = n + 10; } Queue<Integer> q = new LinkedList<>(); boolean vis[] = new boolean[n+1]; dist[a] = 0; q.add(a); while (!q.isEmpty()) { int p = q.poll(); if (vis[p] == true) { continue; } vis[p] = true; for (Integer i : g[p]) { if (!vis[i]) { dist[i] = Integer.min(dist[i], dist[p] + 1); q.add(i); } } } return dist; } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
eaf95bf0d509f0e1219589f55b3284a3
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class Solution { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { String[] input = br.readLine().split(" "); int n = Integer.parseInt(input[0]); int m = Integer.parseInt(input[1]); int a = Integer.parseInt(input[2]); int b = Integer.parseInt(input[3]); int c = Integer.parseInt(input[4]); int[] prices = new int[m]; input = br.readLine().split(" "); for (int i = 0; i < m; i++) prices[i] = Integer.parseInt(input[i]); int[][] edges = new int[m][2]; for (int i = 0; i < m; i++) { input = br.readLine().split(" "); edges[i][0] = Integer.parseInt(input[0]); edges[i][1] = Integer.parseInt(input[1]); } System.out.println(minPrice(prices, edges, n, m, a, b, c)); } } static List<List<Integer>> adjList; private static long minPrice(int[] prices, int[][] edges, int n, int m, int a, int b, int c) { Arrays.sort(prices); long[] pre = new long[m + 1]; for (int i = 0; i < m; i++) pre[i + 1] = pre[i] + prices[i]; adjList = new ArrayList<>(); for (int i = 0; i < n; i++) adjList.add(new ArrayList<>()); for (int i = 0; i < m; i++) { int x = edges[i][0] - 1; int y = edges[i][1] - 1; adjList.get(x).add(y); adjList.get(y).add(x); } int[] dista = new int[n]; int[] distb = new int[n]; int[] distc = new int[n]; Arrays.fill(dista, Integer.MAX_VALUE); Arrays.fill(distb, Integer.MAX_VALUE); Arrays.fill(distc, Integer.MAX_VALUE); bfs(a, dista); bfs(b, distb); bfs(c, distc); long ans = Long.MAX_VALUE; for (int i = 0; i < n; i++) { if(dista[i] + distb[i] + distc[i] > m) continue; ans = Math.min(ans, pre[distb[i]] + pre[dista[i] + distb[i] + distc[i]]); } return ans; } private static void bfs(int start, int[] dist) { start--; dist[start] = 0; Queue<Integer> q = new LinkedList<>(); q.add(start); while (!q.isEmpty()) { int t = q.poll(); for (int c : adjList.get(t)) { if (dist[c] == Integer.MAX_VALUE) { q.add(c); dist[c] = dist[t] + 1; } } } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
d59f6929d1cc0d10394cb8f1ec35260a
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
256 megabytes
import java.util.*; import java.io.*; public class E { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(in.readLine()); for (int i = 0; i < t; i++) { StringTokenizer token = new StringTokenizer(in.readLine()); int n = Integer.parseInt(token.nextToken()); int m = Integer.parseInt(token.nextToken()); int A = Integer.parseInt(token.nextToken()) - 1; int B = Integer.parseInt(token.nextToken()) - 1; int C = Integer.parseInt(token.nextToken()) - 1; int[] p = new int[m]; token = new StringTokenizer(in.readLine()); for(int a = 0; a < m; a++) p[a] = Integer.parseInt(token.nextToken()); Arrays.sort(p); ArrayList<Integer>[] adj = new ArrayList[n]; for(int a = 0; a < n; a++) adj[a] = new ArrayList<Integer>(); for(int a = 0; a < m; a++) { token = new StringTokenizer(in.readLine()); int x = Integer.parseInt(token.nextToken()) - 1; int y = Integer.parseInt(token.nextToken()) - 1; adj[x].add(y); adj[y].add(x); } boolean[] visited = new boolean[n]; int[] disA = new int[n]; LinkedList<Integer> Q = new LinkedList<Integer>(); Q.add(A); visited[A] = true; while(!Q.isEmpty()) { int temp = Q.poll(); for(int a : adj[temp]) if(!visited[a]) { disA[a] = disA[temp] + 1; visited[a] = true; Q.add(a); } } visited = new boolean[n]; int[] disB = new int[n]; Q.add(B); visited[B] = true; while(!Q.isEmpty()) { int temp = Q.poll(); for(int a : adj[temp]) if(!visited[a]) { disB[a] = disB[temp] + 1; visited[a] = true; Q.add(a); } } visited = new boolean[n]; int[] disC = new int[n]; Q.add(C); visited[C] = true; while(!Q.isEmpty()) { int temp = Q.poll(); for(int a : adj[temp]) if(!visited[a]) { disC[a] = disC[temp] + 1; visited[a] = true; Q.add(a); } } long[] prefix = new long[m]; prefix[0] = p[0]; for(int a = 1; a < m; a++) prefix[a] = prefix[a - 1] + p[a]; long best = Long.MAX_VALUE; for(int a = 0; a < n; a++) { int total = disA[a] + disB[a] + disC[a]; if(total > m) continue; best = Math.min(best, (disB[a] > 0 ? prefix[disB[a] - 1] : 0) + (total > 0 ? prefix[total - 1] : 0)); } System.out.println(best); } } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
d7203483e4f7659e362f90269ad836b2
train_002.jsonl
1587479700
You are given an undirected unweighted graph consisting of $$$n$$$ vertices and $$$m$$$ edges (which represents the map of Bertown) and the array of prices $$$p$$$ of length $$$m$$$. It is guaranteed that there is a path between each pair of vertices (districts).Mike has planned a trip from the vertex (district) $$$a$$$ to the vertex (district) $$$b$$$ and then from the vertex (district) $$$b$$$ to the vertex (district) $$$c$$$. He can visit the same district twice or more. But there is one issue: authorities of the city want to set a price for using the road so if someone goes along the road then he should pay the price corresponding to this road (he pays each time he goes along the road). The list of prices that will be used $$$p$$$ is ready and they just want to distribute it between all roads in the town in such a way that each price from the array corresponds to exactly one road.You are a good friend of Mike (and suddenly a mayor of Bertown) and want to help him to make his trip as cheap as possible. So, your task is to distribute prices between roads in such a way that if Mike chooses the optimal path then the price of the trip is the minimum possible. Note that you cannot rearrange prices after the start of the trip.You have to answer $$$t$$$ independent test cases.
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(); } //User-defined functions goes here... class pair{ int x, y; pair(int x, int y){ this.x = x; this.y = y; } } void swap(int[] a, int pos1, int pos2){ int temp = a[pos1]; a[pos1] = a[pos2]; a[pos2] = temp; } boolean powerof2(int n){ return ((n > 2) && ((n & (n-1)) == 0)); } void bfs(int st, int[] dist){ Queue<Integer> q = new LinkedList<>(); dist[st] = 0; q.add(st); while(q.size()>0){ int temp = q.poll(); for (int i: graph[temp]) { if(dist[i] == Integer.MAX_VALUE){ q.add(i); dist[i] = dist[temp] + 1; } } } } ArrayList<Integer>[] graph; public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); //Your code goes here... int test = sc.nextInt(); for (int q0=0; q0<test; q0++) { int n = sc.nextInt(); int m = sc.nextInt(); int a = sc.nextInt()-1; int b = sc.nextInt()-1; int c = sc.nextInt()-1; int p[] = new int[m]; for (int i=0; i<m; i++) { p[i] = sc.nextInt(); } long pref[] = new long[m+1]; Arrays.sort(p); for (int i=1; i<=m; i++) { pref[i] = pref[i-1] + 1l*p[i-1]; } graph = new ArrayList[n]; for (int i=0; i<n; i++) { graph[i] = new ArrayList<>(); } for (int i=0; i<m; i++) { int u = sc.nextInt()-1; int v = sc.nextInt()-1; graph[u].add(v); graph[v].add(u); } int dista[] = new int[n]; Arrays.fill(dista, Integer.MAX_VALUE); int distb[] = new int[n]; Arrays.fill(distb, Integer.MAX_VALUE); int distc[] = new int[n]; Arrays.fill(distc, Integer.MAX_VALUE); bfs(a, dista); bfs(b, distb); bfs(c, distc); long ans = Long.MAX_VALUE; for (int i=0; i<n; i++) { if(dista[i]+distb[i]+distc[i] > m) continue; ans = Math.min(ans, pref[distb[i]] + pref[dista[i]+distb[i]+distc[i]]); } w.println(ans); } w.close(); } }
Java
["2\n4 3 2 3 4\n1 2 3\n1 2\n1 3\n1 4\n7 9 1 5 7\n2 10 4 8 5 6 7 3 3\n1 2\n1 3\n1 4\n3 2\n3 5\n4 2\n5 6\n1 7\n6 7"]
2 seconds
["7\n12"]
NoteOne of the possible solution to the first test case of the example:One of the possible solution to the second test case of the example:
Java 8
standard input
[ "greedy", "graphs", "shortest paths", "sortings", "brute force" ]
89be93cb82d9686ff099d156c309c146
The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains five integers $$$n, m, a, b$$$ and $$$c$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$n-1 \le m \le min(\frac{n(n-1)}{2}, 2 \cdot 10^5)$$$, $$$1 \le a, b, c \le n$$$) — the number of vertices, the number of edges and districts in Mike's trip. The second line of the test case contains $$$m$$$ integers $$$p_1, p_2, \dots, p_m$$$ ($$$1 \le p_i \le 10^9$$$), where $$$p_i$$$ is the $$$i$$$-th price from the array. The following $$$m$$$ lines of the test case denote edges: edge $$$i$$$ is represented by a pair of integers $$$v_i$$$, $$$u_i$$$ ($$$1 \le v_i, u_i \le n$$$, $$$u_i \ne v_i$$$), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair ($$$v_i, u_i$$$) there are no other pairs ($$$v_i, u_i$$$) or ($$$u_i, v_i$$$) in the array of edges, and for each pair $$$(v_i, u_i)$$$ the condition $$$v_i \ne u_i$$$ is satisfied. It is guaranteed that the given graph is connected. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$m$$$) does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum m \le 2 \cdot 10^5$$$).
2,100
For each test case, print the answer — the minimum possible price of Mike's trip if you distribute prices between edges optimally.
standard output
PASSED
bb5651f23bc6a27ef724544d17299037
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Problem_850B { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int M = 2000000 + 10; static int[] cnt = new int[M]; static long[] sum = new long[M]; public static void main(String[] args) { int n = in.nextInt(); long x = in.nextLong(); long y = in.nextLong(); for(int i=0; i<n; ++i) { int val = in.nextInt(); cnt[val]++; sum[val] += val; } for(int i=1; i < M; ++i) { cnt[i] += cnt[i-1]; sum[i] += sum[i-1]; } int ratio = (int)(x/y); boolean[] v = new boolean[M]; long ans = x * n; for(int i=2; i<M; ++i) { if(v[i]) continue; long cur = 0; for(int j=i; j < M; j += i) { v[j] = true; int left = j - i + 1; int cutoff = j - ratio - 1; if(cutoff < left) cutoff = left - 1; cur += cnt(left, cutoff) * x; cur += (cnt(cutoff+1, j-1) * j - sum(cutoff+1, j-1)) * y; } ans = Math.min(ans, cur); } System.out.println(ans); out.close(); } static long cnt(int l, int r) { if(l > r) return 0; return cnt[r] - cnt[l-1]; } static long sum(int l, int r) { if(l > r) return 0; return sum[r] - sum[l-1]; } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
337b15448dc5afe5db2e0e28e3eaa986
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.util.*; public class B850 { public static void main(String[] args) throws IOException { IO io = new IO(System.in); int max_a = 1000005; ArrayList<Integer> primes = sieve(max_a); int n = io.nextInt(); int x = io.nextInt(); // delete int y = io.nextInt(); // increment long[] count = new long[max_a]; for (int i = 0; i < n; i++) { int a = io.nextInt(); // int a = 1; count[a]++; } long[] cnt = new long[max_a]; long[] sum = new long[max_a]; for (int i = 1; i < sum.length; i++) { cnt[i] = cnt[i-1] + count[i]; sum[i] = sum[i-1] + (long) i * count[i]; } // max amount of increments that is cheaper than 1 delete int len = x / y; long best = Long.MAX_VALUE; for (int p : primes) { // use p as gcd long cst = 0; int total_inc = 0; for (int cur = p; cur - p < max_a; cur+=p) { // Determine numbers better to increment // Out of numbers between cur-p+1 and cur int start = Math.max(cur - p +1, cur-len); int end = Math.min(max_a-1, cur); if (start <= end) { // Increment all numbers start, start+1,...,end instead of remove long nr = cnt[end]-cnt[start-1]; // Sum of numbers that are getting increment long s = sum[end]-sum[start-1]; total_inc += nr; cst += ((long) cur * nr - s)*y; } } cst += (n-total_inc) * (long) x; best = Math.min(best, cst); } io.println(best); io.close(); } // return ArrayList<Integer> of all primes <= n. static ArrayList<Integer> sieve(int n) { ArrayList<Integer> res = new ArrayList<Integer>(); boolean[] notPrime = new boolean[n + 1]; for (int i = 2; i <= n; i++) { if (!notPrime[i]) { res.add(i); for (int j = 2; j * i <= n; j++) { notPrime[i * j] = true; } } } return res; } static class IO extends PrintWriter { static BufferedReader r; static StringTokenizer t; public IO(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); t = new StringTokenizer(""); } public String next() throws IOException { while (!t.hasMoreTokens()) { t = new StringTokenizer(r.readLine()); } return t.nextToken(); } 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
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
09d40b4fc626ded080795d2ada113b51
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { static InputReader in = new InputReader(System.in); static PrintWriter out = new PrintWriter(System.out); static int M = 2000000 + 10; static int[] cnt = new int[M]; static long[] sum = new long[M]; public static void main(String[] args) { int n = in.nextInt(); long x = in.nextLong(); long y = in.nextLong(); for(int i=0; i<n; ++i) { int val = in.nextInt(); cnt[val]++; sum[val] += val; } for(int i=1; i < M; ++i) { cnt[i] += cnt[i-1]; sum[i] += sum[i-1]; } int ratio = (int)(x/y); boolean[] v = new boolean[M]; long ans = x * n; for(int i=2; i<M; ++i) { if(v[i]) continue; long cur = 0; for(int j=i; j < M; j += i) { v[j] = true; int left = j - i + 1; int cutoff = j - ratio - 1; if(cutoff < left) cutoff = left - 1; cur += cnt(left, cutoff) * x; cur += (cnt(cutoff+1, j-1) * j - sum(cutoff+1, j-1)) * y; } ans = Math.min(ans, cur); } System.out.println(ans); out.close(); } static long cnt(int l, int r) { if(l > r) return 0; return cnt[r] - cnt[l-1]; } static long sum(int l, int r) { if(l > r) return 0; return sum[r] - sum[l-1]; } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
6b73e9a25ff6021c282c28b5e95a2dce
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.io.Closeable; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) throws Exception { Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27); thread.start(); thread.join(); } static class TaskAdapter implements Runnable { @Override public void run() { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastInput in = new FastInput(inputStream); FastOutput out = new FastOutput(outputStream); BArpaAndAListOfNumbers solver = new BArpaAndAListOfNumbers(); solver.solve(1, in, out); out.close(); } } static class BArpaAndAListOfNumbers { public void solve(int testNumber, FastInput in, FastOutput out) { int n = in.readInt(); long x = in.readLong(); long y = in.readLong(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.readInt(); } long ans = n * x; int limit = 2000000; int[] cnts = new int[limit + 1]; long[] sum = new long[limit + 1]; for (int v : a) { cnts[v]++; sum[v] += v; } IntegerPreSum cPs = new IntegerPreSum(i -> cnts[i], limit + 1); LongPreSum sPs = new LongPreSum(i -> sum[i], limit + 1); for (int i = 2; i <= limit; i++) { //ky >= x => k >= x / y int k = (int) DigitUtils.ceilDiv(x, y); long req = 0; for (int j = i; j <= limit; j += i) { int l = j - i + 1; int r = j; int threshold = r - k; if (l <= threshold) { req += x * cPs.intervalSum(l, threshold); req += y * ((long) cPs.intervalSum(threshold + 1, r) * j - sPs.intervalSum(threshold + 1, r)); } else { req += y * ((long) cPs.intervalSum(l, r) * j - sPs.intervalSum(l, r)); } } ans = Math.min(ans, req); } out.println(ans); } } static interface IntToIntegerFunction { int apply(int x); } static class FastOutput implements AutoCloseable, Closeable, Appendable { private StringBuilder cache = new StringBuilder(10 << 20); private final Writer os; public FastOutput append(CharSequence csq) { cache.append(csq); return this; } public FastOutput append(CharSequence csq, int start, int end) { cache.append(csq, start, end); return this; } public FastOutput(Writer os) { this.os = os; } public FastOutput(OutputStream os) { this(new OutputStreamWriter(os)); } public FastOutput append(char c) { cache.append(c); return this; } public FastOutput append(long c) { cache.append(c); return this; } public FastOutput println(long c) { return append(c).println(); } public FastOutput println() { cache.append(System.lineSeparator()); return this; } public FastOutput flush() { try { os.append(cache); os.flush(); cache.setLength(0); } catch (IOException e) { throw new UncheckedIOException(e); } return this; } public void close() { flush(); try { os.close(); } catch (IOException e) { throw new UncheckedIOException(e); } } public String toString() { return cache.toString(); } } static interface IntToLongFunction { long apply(int x); } static class DigitUtils { private DigitUtils() { } public static long floorDiv(long a, long b) { return a < 0 ? -ceilDiv(-a, b) : a / b; } public static long ceilDiv(long a, long b) { if (a < 0) { return -floorDiv(-a, b); } long c = a / b; if (c * b < a) { return c + 1; } return c; } } static class LongPreSum { private long[] pre; private int n; public LongPreSum(int n) { pre = new long[n]; } public void populate(IntToLongFunction a, int n) { this.n = n; pre[0] = a.apply(0); for (int i = 1; i < n; i++) { pre[i] = pre[i - 1] + a.apply(i); } } public LongPreSum(IntToLongFunction a, int n) { this(n); populate(a, n); } public long intervalSum(int l, int r) { return prefix(r) - prefix(l - 1); } public long prefix(int i) { if (i < 0) { return 0; } return pre[Math.min(i, n - 1)]; } } static class FastInput { private final InputStream is; private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastInput(InputStream is) { this.is = is; } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { bufLen = -1; } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } } static class IntegerPreSum { private int[] pre; private int n; public IntegerPreSum(int n) { pre = new int[n]; } public void populate(IntToIntegerFunction a, int n) { this.n = n; pre[0] = a.apply(0); for (int i = 1; i < n; i++) { pre[i] = pre[i - 1] + a.apply(i); } } public IntegerPreSum(IntToIntegerFunction a, int n) { this(n); populate(a, n); } public int intervalSum(int l, int r) { return prefix(r) - prefix(l - 1); } public int prefix(int i) { if (i < 0) { return 0; } return pre[Math.min(i, n - 1)]; } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
dd02a9303360b0f31e2aaca246c306ad
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main{ public static long getSum(int from, int to, long[] pref){ if(from <=0){ return pref[to]; } else { return pref[to]-pref[from-1]; } } public static long count(long p, long[] pref, long[] sums, long x, long y){ long res = 0L; int id = (int)x/(int)y+1; if(id >= p){ id = (int)p; } for(int j = (int)p; j < 1048576+p; j+=p){ res += getSum(j-(int)p+1, j-id, pref)*x; res += (getSum(j-id+1, j, pref)*j - getSum(j-id+1, j, sums))*y; } return res; } public static void main(String[] args){ InputReader reader = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); int n = reader.nextInt(); int x = reader.nextInt(); int y = reader.nextInt(); long[] pref = new long[2*1048576]; long[] sums = new long[2*1048576]; for(int i=0; i<n; ++i){ int number = reader.nextInt(); pref[number]++; sums[number]+= number; } for(int i=1; i<2*1048576; ++i){ pref[i]+=pref[i-1]; sums[i]+=sums[i-1]; } boolean[] composite = new boolean[2*1048576]; for(int i=2; i*i<2*1048576; ++i){ if(!composite[i]){ for(int j=i*i; j<2*1048576; j+=i){ composite[j] = true; } } } long res = Long.MAX_VALUE; for(int i=2; i<2*1048576; ++i){ if(!composite[i]){ res = Math.min(res, count(i, pref, sums, x, y)); } } pw.println(res); pw.flush(); pw.close(); } public static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader (InputStream stream){ reader = new BufferedReader(new InputStreamReader(stream)); } public String next(){ while(tokenizer == null || !tokenizer.hasMoreTokens()){ try{ String line = reader.readLine(); if(line == null){ return "0"; } tokenizer = new StringTokenizer(line); } catch(IOException ioe){ throw new RuntimeException(ioe); } } return tokenizer.nextToken(); } public int nextInt(){ return Integer.parseInt(next()); } public double nextDouble(){ return Double.parseDouble(next()); } public Long nextLong(){ return Long.parseLong(next()); } public BigInteger nextBigInteger(){ return new BigInteger(next()); } public String nextLine(){ String line = ""; try{ while(line.equals("")){ line = reader.readLine(); } } catch(IOException ioe){ throw new RuntimeException(ioe); } return line; } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
7724eb747bf9b62e0c51e3691c146c6d
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.util.*; public class Solution { static MyScanner sc; private static PrintWriter out; public static void main(String[] s) throws Exception { sc = new MyScanner(System.in); // sc = new MyScanner(new BufferedReader(new StringReader("4 20 10 1 2 3 4"))); // sc = new MyScanner(new BufferedReader(new StringReader("5\n" + // "4 6 4 4 6\n" + // "1 2 \n" + // "2 3 \n" + // "3 4\n" + // "4 5"))); out = new PrintWriter(new OutputStreamWriter(System.out)); long t = System.currentTimeMillis(); solve(); out.flush(); } private static void solve() { int n = sc.nextInt(); int x = sc.nextInt(); int y = sc.nextInt(); int[] t = sc.na(n); long[] sum = new long[1000001]; long[] ct = new long[1000001]; for (int k : t) { sum[k] += k; ct[k] += 1; } for (int i = 1; i <= 1000000; i++) { ct[i] += ct[i - 1]; sum[i] += sum[i - 1]; } int rt = x / y; long m = Long.MAX_VALUE; for (int k = 2; k <= 1000000; k++) { long cur = 0; int e1 = Math.max(k - rt - 1, 0); for (int kx = 0; kx * k < 1000000; kx++) { int f1 = Math.min(kx * k + e1, 1000000); int f2 = Math.min(kx * k + k - 1, 1000000); cur += x * (ct[f1] - ct[kx * k]); cur += y * ((ct[f2] - ct[f1]) * (kx + 1) * k - sum[f2] + sum[f1]); } m = Math.min(cur, m); } System.out.println(m); } private static void solveT() { int t = sc.nextInt(); while (t-- > 0) { solve(); } } private static long gcd(long l, long l1) { if (l > l1) return gcd(l1, l); if (l == 0) return l1; return gcd(l1 % l, l); } private static long pow(long a, long b, long m) { if (b == 0) return 1; if (b == 1) return a; long pp = pow(a, b / 2, m); pp *= pp; pp %= m; return (pp * (b % 2 == 0 ? 1 : a)) % m; } static class MyScanner { BufferedReader br; StringTokenizer st; MyScanner(BufferedReader br) { this.br = br; } public MyScanner(InputStream in) { this(new BufferedReader(new InputStreamReader(in))); } void findToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } } String next() { findToken(); return st.nextToken(); } int[] na(int n) { int[] k = new int[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextInt(); } return k; } long[] nl(int n) { long[] k = new long[n]; for (int i = 0; i < n; i++) { k[i] = sc.nextLong(); } return k; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
ce9b816a2c6f4a860b39fb2e43b138de
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces850B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken()); int[] a = new int[n]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(st.nextToken()); } int N = 1000001; //list of primes boolean[] primeList = new boolean[N+1]; for (int i = 2; i <= N; i++) { primeList[i] = true; } for (int i = 2; i <= N; i++) { for (int j = 2; j <= N/i; j++) { primeList[i*j] = false; } } //number of prime factors (without multiplicity) int[] numprime = new int[N+1]; for (int i = 2; i < N+1; i++) { if (numprime[i] == 0) { for (int j = 1; j <= N/i; j++) { numprime[i*j]++; } } } //list of prime factors (without multiplicity) int[][] listprime = new int[N+1][]; for (int i = 0; i <= N; i++) { listprime[i] = new int[numprime[i]]; } int[] counter = new int[N+1]; for (int i = 2; i <= N; i++) { if (primeList[i]) { for (int j = 1; j <= N/i; j++) { listprime[i*j][counter[i*j]] = i; counter[i*j]++; } } } if (x <= y) { int[] possible = new int[N+1]; for (int i = 0; i < n; i++) { int k = numprime[a[i]]; for (int j = 0; j < k; j++) { possible[listprime[a[i]][j]]++; } } long min = (long) n; for (int i = 0; i <= N; i++) { min = Math.min(min, n-possible[i]); } min *= x; System.out.println(min); } else if (x <= 2*y) { int[] success = new int[N+1]; int[] oneoff = new int[N+1]; for (int i = 0; i < n; i++) { int k = numprime[a[i]]; for (int j = 0; j < k; j++) { success[listprime[a[i]][j]]++; } k = numprime[a[i]+1]; for (int j = 0; j < k; j++) { oneoff[listprime[a[i]+1][j]]++; } } long min = (long) n * (long) x; for (int i = 2; i <= N; i++) { if (primeList[i]) { long cost = (long) oneoff[i] * (long) y + (long) (n-oneoff[i]-success[i]) * (long) x; min = Math.min(cost, min); } } pw.println(min); } else { int[] possible = new int[N+1]; for (int i = 0; i < n; i++) { int k = numprime[a[i]]; for (int j = 0; j < k; j++) { possible[listprime[a[i]][j]] += 2; } k = numprime[a[i]+1]; for (int j = 0; j < k; j++) { possible[listprime[a[i]+1][j]]++; } } long min = (long) n * (long) x; for (int i = 2; i <= N; i++) { if (possible[i] >= possible[2]) { long cost = 0; for (int j = 0; j < n; j++) { if (a[j]%i > 0) { cost += Math.min((long) x, (long) y * (long) (i-a[j]%i)); } } min = Math.min(cost, min); } } pw.println(min); } pw.close(); } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
d535c3a802ac385d7a09189f4f8ac8df
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.util.StringTokenizer; /** * Created by fly on 9/4/17. */ public class Main { public static int mod = 1_000_000_007; public static int size = 2_000_000; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); int n = in.nextInt(); int x = in.nextInt(); int y = in.nextInt(); long[] sum = new long[size + 1]; long[] count = new long[size + 1]; boolean[] isNotPrime = new boolean[size + 1]; for (int i = 1; i <= n; ++i) { int num = in.nextInt(); sum[num] += num; ++count[num]; } for (int i = 1; i <= size; ++i) { sum[i] += sum[i - 1]; count[i] += count[i - 1]; } long res = Long.MAX_VALUE; for (int i = 2; i <= size; ++i) { if (!isNotPrime[i]) { for (int s = i * 2; s <= size; s += i) isNotPrime[i] = true; int rate = Math.min(x / y + 1, i); long temp = 0; for (int s = i; s <= size; s += i) { temp += ((count[s] - count[s - rate]) * s - (sum[s] - sum[s - rate])) * y + (count[s - rate] - count[s - i]) * x; } res = Math.min(res, temp); } } out.println(res); 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) { e.printStackTrace(); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
3c65d4de2c8e23c5c74be68a58917a85
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
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.StringTokenizer; public class Main { static BufferedReader reader; static StringTokenizer tokenizer; static PrintWriter writer; static String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } static int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); banana(); reader.close(); writer.close(); } static int N = 1000002; static int[] lp = new int[N + 1]; static ArrayList<Integer> pr = new ArrayList<>(); static void init() { for (int i = 2; i <= N; i++) { if (lp[i] == 0) { lp[i] = i; pr.add(i); } for (int j = 0; j < (int) pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= N; j++) { lp[i * pr.get(j)] = pr.get(j); } } } static void banana() throws NumberFormatException, IOException { init(); int n = nextInt(); long x = nextInt(); long y = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { // TODO: // a[i] = ((int) (1000000 * Math.random())) + 1; a[i] = nextInt(); } int[] free = new int[1000002]; for (int t : a) { for (int p : pr) { if (t == 1) { break; } if (p * p > t) { free[t]++; break; } if (t % p == 0) { free[p]++; while (t % p == 0) { t /= p; } } } } long res = Long.MAX_VALUE; for (int cand : pr) { long minEstimate = (n - free[cand]) * (Math.min(x, y)); if (minEstimate >= res) { continue; } long curr = 0; for (int p : a) { long upto = ((cand - p % cand) % cand) * y; if (x < upto) { curr += x; } else { curr += upto; } if (curr >= res) { break; } } if (curr < res) { res = curr; } } writer.println(res); } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
9c4fcb5b0e3c3005c38b223900088ae8
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " :"); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } final int MAX = 2000000 + 100; void solve() throws IOException { int n = readInt(); int x = readInt(); int y = readInt(); int[] a = readIntArray(n); int[] cnt = new int[MAX + 1]; for (int val : a) cnt[val]++; int[] countPrefix = new int[MAX + 1]; long[] valuePrefix = new long[MAX + 1]; for (int i = 1; i <= MAX; i++) { countPrefix[i] = countPrefix[i - 1] + cnt[i]; valuePrefix[i] = valuePrefix[i - 1] + (long) cnt[i] * i; } long bestAnswer = (long) x * n; for (int gcd = 2; gcd <= MAX; gcd++) { int last = 0; long curAnswer = 0; for (int curMul = gcd; curMul <= MAX; curMul += gcd) { int cntRight = x / y; int ly = Math.max(last, curMul - cntRight); int ry = curMul; int lx = last; int rx = ly - 1; long curAdd = ((long) curMul * get(countPrefix, ly, ry) - get(valuePrefix, ly, ry)) * y; curAdd += (long) x * get(countPrefix, lx, rx); curAnswer += curAdd; last = curMul + 1; } bestAnswer = Math.min(bestAnswer, curAnswer); } out.println(bestAnswer); } long get(long[] arr, int l, int r) { if (l > r) return 0; long val = arr[r]; if (l > 0) val -= arr[l - 1]; return val; } int get(int[] arr, int l, int r) { if (l > r) return 0; int val = arr[r]; if (l > 0) val -= arr[l - 1]; return val; } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
0cdf208ba281e6ac7f881e888046679c
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class b implements Runnable { PrintWriter out; int M, n; int[] arr; long x, y, counts[], sums[]; public void main() throws Throwable { FastScanner in = new FastScanner(System.in); out = new PrintWriter(System.out); M = 1000100; n = in.nextInt(); x = in.nextLong(); y = in.nextLong(); arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = in.nextInt(); counts = new long[M]; sums = new long[M]; for (int a : arr) { counts[a]++; sums[a] += a; } for (int i = 1; i < M; i++) { counts[i] += counts[i - 1]; sums[i] += sums[i - 1]; } int[] primes = primeSieve(M); long min = x * n; for (int p = 2; p < M; p++) { if (primes[p] != p) continue; long cost = 0; int ca = (int) (x / y); for (int s = 1; s <= 1000000; s += p) { int b = s + p - 2; int cut = s + p - 2 - ca; if (cut < s) cut = s - 1; cost += x * getCount(s, cut); cost += y * (getCount(cut + 1, b) * (s + p - 1) - getSum(cut + 1, b)); } min = Math.min(min, cost); } out.println(min); out.close(); } // Linear prime sieve, but forces you to save the smallest prime factors (more memory) // Useful when you need to factor numbers in a large range, but not all of them (like the above function) static int[] primeSieve(int N) { int[] lp = new int[N + 1]; int[] pr = new int[N + 1]; // could shrink this to the number of primes int prSize = 0; for (int i = 2; i <= N; ++i) { if (lp[i] == 0) { lp[i] = i; pr[prSize++] = i; } int ub = Math.min(lp[i], N / i); for (int j = 0; j < prSize && pr[j] <= ub; ++j) { lp[i * pr[j]] = pr[j]; } } return lp; } long getSum(int a, int b) { a = Math.max(a, 1); b = Math.min(b, sums.length - 1); if (a > b) return 0; return sums[b] - sums[a - 1]; } long getCount(int a, int b) { a = Math.max(a, 1); b = Math.min(b, counts.length - 1); if (a > b) return 0; return counts[b] - counts[a - 1]; } public static void main(String[] args) throws Exception { new Thread(null, new b(), "b", 1L << 29).start(); } public void run() { try { main(); } catch (Throwable t) { t.printStackTrace(); System.exit(-1); } } static void sort(int[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 1; i < n; i++) { int j = rand.nextInt(i); int tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } Arrays.sort(arr); } static void sort(long[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int j = rand.nextInt(i); long tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } Arrays.sort(arr); } static void sort(double[] arr) { Random rand = new Random(); int n = arr.length; for (int i = 0; i < n; i++) { int j = rand.nextInt(i); double tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } Arrays.sort(arr); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream i) { br = new BufferedReader(new InputStreamReader(i)); st = new StringTokenizer(""); } public String next() throws Exception { while (!st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public int[] nextIntArr(int n) throws Exception { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } public double[] nextDoubleArr(int n) throws Exception { double[] arr = new double[n]; for (int i = 0; i < n; i++) arr[i] = nextDouble(); return arr; } public long[] nextLongArr(int n) throws Exception { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } public int[] nextOffsetIntArr(int n) throws Exception { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt() - 1; return arr; } public int[][] nextIntArr(int n, int m) throws Exception { int[][] arr = new int[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextInt(); return arr; } public double[][] nextDoubleArr(int n, int m) throws Exception { double[][] arr = new double[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextDouble(); return arr; } public long[][] nextLongArr(int n, int m) throws Exception { long[][] arr = new long[n][m]; for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) arr[i][j] = nextLong(); return arr; } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
6855803a69b4c5d64c5af20cf2f962a4
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { int MAX = (int) 1e6 + 1; int[] cnt; long[] sum; int X; int Y; public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); X = in.nextInt(); Y = in.nextInt(); int[] A = new int[N]; cnt = new int[2 * MAX]; sum = new long[2 * MAX]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); cnt[A[i]]++; sum[A[i]] += A[i]; } for (int i = 1; i < 2 * MAX; i++) { cnt[i] += cnt[i - 1]; sum[i] += sum[i - 1]; } boolean[] composite = new boolean[MAX]; long ans = Long.MAX_VALUE; for (int i = 2; i < MAX; i++) { if (!composite[i]) { ans = Math.min(ans, find(i)); for (int j = 2 * i; j < MAX; j += i) { composite[j] = true; } } } out.println(ans); } private long find(int g) { long ans = 0; for (int k = g; k < 2 * MAX; k += g) { //we need to sum ranges (k-g,f] and (f, k], int f = k - Math.min(g, (X + Y - 1) / Y); long prefix = cnt(k - g + 1, f); long suffix = cnt(f + 1, k); long prefixSum = sum(f + 1, k); ans += prefix * X + Y * (k * suffix - prefixSum); } return ans; } private long sum(int left, int right) { return sum[right] - sum[left - 1]; } private long cnt(int left, int right) { return cnt[right] - cnt[left - 1]; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
82f09a939bc84644c6dc5416b6ace5d5
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
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 B_Round_432_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(); long x = in.nextInt(); long y = in.nextInt(); int[] count = new int[1000001]; int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); count[data[i]]++; } Arrays.sort(data); long re = ((long) (n - 1)) * x; if (data[n - 1] == 1) { re = Long.min(((long) n * y), (long) (n - 1) * x + y); } boolean[] check = new boolean[count.length]; int[] total = new int[count.length]; ArrayList<Integer> set = new ArrayList(); for (int i = 2; i < check.length; i++) { if (!check[i]) { total[i] += count[i]; for (int j = i + i; j < check.length; j += i) { check[j] = true; total[i] += count[j]; } if (total[i] > 0) { set.add(i); } } } if (set.isEmpty() || set.get(0) != 2) { set.add(2); } //System.out.println(Arrays.toString(data)); for (int i = 2; i < total.length; i++) { int left = n - total[i]; re = Long.min(left * x, re); } if (x > y) { long[] pre = new long[n]; for (int i = 0; i < n; i++) { pre[i] = (long) data[i] + (i > 0 ? pre[i - 1] : 0); } for (int i : set) { int nxt = 0; long cur = 0; int index; int other; for (int j = i; j - i <= data[n - 1] && nxt < n; j += i) { int st = nxt; int ed = n - 1; index = nxt; while (st <= ed) { int mid = (st + ed) / 2; if (data[mid] >= j) { index = mid; ed = mid - 1; } else { st = mid + 1; } } if (data[n - 1] < j) { index = n; } st = nxt; ed = index - 1; other = -1; while (st <= ed) { int mid = (st + ed) / 2; long v = (i - (data[mid] % i)) * y; if (v >= x) { other = mid; st = mid + 1; } else { ed = mid - 1; } } if (other != -1) { cur += (other - nxt + 1) * x; long left = index - other - 1; long sum = pre[index - 1] - pre[other]; cur += ((long) j * left - sum) * y; } else if (index != nxt) { long tmp = (long) (index - nxt); tmp *= (long) j; cur += (tmp - (pre[index - 1] - (nxt != 0 ? pre[nxt - 1] : 0))) * y; } //System.out.println(Arrays.toString(data)); //System.out.println(j + " " + index + " " + other + " " + nxt + " " + cur); st = index; ed = n - 1; nxt = index; while (st <= ed) { int mid = (st + ed) / 2; if (data[mid] <= j) { nxt = mid + 1; st = mid + 1; } else { ed = mid - 1; } } } re = Long.min(re, cur); } } out.println(re); out.close(); } 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 Integer.compare(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, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); 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
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
409bb990d75b0d3e9fd5ee19a0e5c87b
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
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 B_Round_432_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(); long x = in.nextInt(); long y = in.nextInt(); int[] count = new int[1000001]; int[] data = new int[n]; for (int i = 0; i < n; i++) { data[i] = in.nextInt(); count[data[i]]++; } Arrays.sort(data); long re = ((long) (n - 1)) * x; if (data[n - 1] == 1) { re = Long.min(((long) n * y), (long) (n - 1) * x + y); } boolean[] check = new boolean[count.length]; int[] total = new int[count.length]; ArrayList<Integer> set = new ArrayList(); for (int i = 2; i < check.length; i++) { if (!check[i]) { total[i] += count[i]; for (int j = i + i; j < check.length; j += i) { check[j] = true; total[i] += count[j]; } //if (total[i] > 0) { set.add(i); // } } } //System.out.println(Arrays.toString(data)); for (int i = 2; i < total.length; i++) { int left = n - total[i]; re = Long.min(left * x, re); } if (x > y) { long[] pre = new long[n]; for (int i = 0; i < n; i++) { pre[i] = (long) data[i] + (i > 0 ? pre[i - 1] : 0); } for (int i : set) { int nxt = 0; long cur = 0; int index; int other; for (int j = i; j - i <= data[n - 1] && nxt < n; j += i) { int st = nxt; int ed = n - 1; index = nxt; while (st <= ed) { int mid = (st + ed) / 2; if (data[mid] >= j) { index = mid; ed = mid - 1; } else { st = mid + 1; } } if (data[n - 1] < j) { index = n; } st = nxt; ed = index - 1; other = -1; while (st <= ed) { int mid = (st + ed) / 2; long v = (i - (data[mid] % i)) * y; if (v >= x) { other = mid; st = mid + 1; } else { ed = mid - 1; } } if (other != -1) { cur += (other - nxt + 1) * x; long left = index - other - 1; long sum = pre[index - 1] - pre[other]; cur += ((long) j * left - sum) * y; } else if (index != nxt) { long tmp = (long) (index - nxt); tmp *= (long) j; cur += (tmp - (pre[index - 1] - (nxt != 0 ? pre[nxt - 1] : 0))) * y; } //System.out.println(Arrays.toString(data)); //System.out.println(j + " " + index + " " + other + " " + nxt + " " + cur); st = index; ed = n - 1; nxt = index; while (st <= ed) { int mid = (st + ed) / 2; if (data[mid] <= j) { nxt = mid + 1; st = mid + 1; } else { ed = mid - 1; } } } re = Long.min(re, cur); } } out.println(re); out.close(); } 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 Integer.compare(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, long MOD) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2, MOD); 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
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
45afe57ffddd0a3298cb075b87b4fd12
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, FastScanner in, PrintWriter out) { final int N = 1000010; int[] a = new int[N]; long[] s1 = new long[N + 1]; long[] s2 = new long[N + 1]; int n = in.nextInt(); long x = in.nextInt(); long y = in.nextInt(); for (int i = 0; i < n; i++) { ++a[in.nextInt()]; } for (int i = 0; i < N; i++) { s1[i + 1] = s1[i] + a[i]; s2[i + 1] = s2[i] + a[i] * (long) i; } long ans = n * x; for (int gcd = 2; gcd < N; gcd++) { long cur = 0; for (int l = 1; l < N; l += gcd) { int r = l - 1 + gcd; int er = Math.min(N - 1, r); int j = clamp((r * y - x) / y, l - 1, r + 1); if (j >= l && j <= r) { j = Math.min(j, N - 1); cur += (s1[j + 1] - s1[l]) * x; long c = (s1[er + 1] - s1[j + 1]) * r; c -= s2[er + 1] - s2[j + 1]; if (c > ans / y) { cur = ans; break; } cur += c * y; if (cur > ans) { break; } } else { long c = (s1[er + 1] - s1[l]) * r; c -= s2[er + 1] - s2[l]; if (c > ans / y) { cur = ans; break; } cur += c * y; if (cur > ans) { break; } } } ans = Math.min(ans, cur); } out.println(ans); } private int clamp(long x, int l, int r) { x = Math.min(x, r); x = Math.max(x, l); return (int) x; } } static class FastScanner { private BufferedReader in; private StringTokenizer st; public FastScanner(InputStream stream) { in = new BufferedReader(new InputStreamReader(stream)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
9ab5dee9110c971f283d8987f6763993
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
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(); long x = sc.nextLong(); long y = sc.nextLong(); int a[] = new int[n]; int freq[] = new int[2000001]; long sum[] = new long[2000001]; for(int i = 0; i < n; ++i) { a[i] = sc.nextInt(); freq[a[i]]++; sum[a[i]] += (long)a[i]; } for(int i = 1; i <= 2000000; ++i) { freq[i] = freq[i - 1] + freq[i]; sum[i] = sum[i - 1] + sum[i]; } long minans = Long.MAX_VALUE; for(long i = 2; i <= 1000000; ++i) { long cost = 0; for(long j = i; ; j += i) { long l1 = j - i; long l2 = j - min(i - 1, x / y) - 1; long r1 = l2; long r2 = j; long cnt1 = freq[(int)r2] - freq[(int)l2]; long cnt2 = freq[(int)r1] - freq[(int)l1]; long sum1 = sum[(int)r2] - sum[(int)l2]; cost += x * cnt2; cost += (cnt1 * j - sum1) * y; if(j >= 1000000) break; } minans = min(cost, minans); } w.print(minans); w.close(); } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
b4c88917782dc3c4164b8bdda75f9a85
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.StringTokenizer; public class R432D1P2 { static List<Long> computeUniquePrimeFactors(long a, List<Long> orderedPrimes) { LinkedList<Long> result = new LinkedList<>(); long quot = a; for (Long p : orderedPrimes) { if (p * p > a) { result.add(quot); break; } if (quot % p == 0) { result.add(p); while (quot % p == 0) { quot /= p; } } if (quot == 1) { break; } } return result; } public static void main(String[] args) throws Exception { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); StringTokenizer st = new StringTokenizer(bf.readLine()); int n = Integer.parseInt(st.nextToken()); long x = Integer.parseInt(st.nextToken()); long y = Integer.parseInt(st.nextToken()); long[] arr = new long[n]; st = new StringTokenizer(bf.readLine()); int max = 0; for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(st.nextToken()); max = Math.max(max, (int) arr[i]); } // int n = 500000; // long x = 1000000000; // long y = 1000000000; // long[] arr = new long[n]; // for (int i = 0; i < n; i++) { // arr[i] = 1000000 - 2 * i - 1; // } // int max = (int) arr[0]; boolean[] isComposite = new boolean[2 * max]; for (int i = 2; i < isComposite.length; i++) { for (int j = 2 * i; j < isComposite.length; j += i) { isComposite[j] = true; } } LinkedList<Long> primes = new LinkedList<>(); for (int i = 2; i < isComposite.length; i++) { if (!isComposite[i]) { primes.add((long) i); } } final Map<Long, Integer> primeCounts = new HashMap<>(); for (int i = 0; i < n; i++) { if (arr[i] == 1) { continue; } if (!isComposite[(int) arr[i]]) { if (primeCounts.containsKey(arr[i])) { primeCounts.put(arr[i], primeCounts.get(arr[i]) + 1); } else { primeCounts.put(arr[i], 1); } continue; } List<Long> primeDecomp = computeUniquePrimeFactors(arr[i], primes); for (Long p : primeDecomp) { if (primeCounts.containsKey(p)) { primeCounts.put(p, primeCounts.get(p) + 1); } else { primeCounts.put(p, 1); } } } // option 1: use gcd=2 long minCost = 0; for (int i = 0; i < n; i++) { minCost += Math.min(x, (arr[i] % 2) * y); } // option 2: use primes // there must be at least 1 prime in the factor set, otherwise using 2 is always better ArrayList<Long> primesByFreq = new ArrayList<>(primeCounts.keySet()); Collections.sort(primesByFreq, new Comparator<Long>() { @Override public int compare(Long a, Long b) { return primeCounts.get(b) - primeCounts.get(a); } }); for (Long p : primesByFreq) { int numNotDivisible = n - primeCounts.get(p); if (numNotDivisible * Math.min(x, y) >= minCost) { // can't do any better break; } long curCost = 0; for (int i = 0; i < n; i++) { if (arr[i] % p == 0) { continue; } curCost += Math.min(x, (p - arr[i] % p) * y); } if (curCost < minCost) { minCost = curCost; } } out.println(minCost); out.close(); } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
8feda624cc4d890b6829eb6544b1b6e6
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.*; import java.util.*; public class B { static final int N = 1_000_010; void submit() { int n = nextInt(); int del = nextInt(); int inc = nextInt(); int len = del / inc; int[] cnt = new int[N]; for (int i = 0; i < n; i++) { int x = nextInt(); cnt[x]++; } int[] prCnt = new int[N]; long[] prSum = new long[N]; for (int i = 1; i < N; i++) { prCnt[i] = prCnt[i - 1] + cnt[i]; prSum[i] = prSum[i - 1] + (long)i * cnt[i]; } PrimeRoutines pr = new PrimeRoutines(N); int[] primes = pr.p; long ans = Long.MAX_VALUE; // if (cnt[1] == n) { // ans = (long)(n - 1) * Math.min(inc, del) + inc; // } else { // ans = (long)(n - 1) * del; // } for (int p : primes) { int removeHere = n; long costHere = 0; for (int where = p; where - p < N; where += p) { int from = Math.max(where - len, where - p + 1); int to = Math.min(where, N - 1); if (from <= to) { int cntHere = prCnt[to] - prCnt[from - 1]; long sumHere = prSum[to] - prSum[from - 1]; removeHere -= cntHere; costHere += (long)where * cntHere - sumHere; } } // if (removeHere == n) { // continue; // } ans = Math.min(ans, (long)removeHere * del + costHere * inc); } out.println(ans); } public class PrimeRoutines { int[] lowDivIdx; int[] lowDiv; int[] p; int N; public PrimeRoutines(int N) { this.N = N; p = new int[(int)(N / Math.log(N))]; lowDivIdx = new int[N + 1]; lowDiv = new int[N + 1]; Arrays.fill(lowDivIdx, -1); int pCnt = 0; for (int i = 2; i <= N; i++) { if (lowDivIdx[i] == -1) { if (p.length == pCnt) { p = Arrays.copyOf(p, 2 * p.length); } lowDivIdx[i] = pCnt; lowDiv[i] = i; p[pCnt++] = i; } int toJ = Math.min(pCnt, lowDivIdx[i] + 1); for (int j = 0; j < toJ; j++) { int x = i * p[j]; if (x > N) { break; } lowDivIdx[x] = j; lowDiv[x] = p[j]; } } p = Arrays.copyOf(p, pCnt); } int[] divCount() { int[] ret = new int[N + 1]; int[] tmp = new int[N + 1]; ret[1] = 1; for (int i = 2; i <= N; i++) { int p = lowDiv[i]; int j = i / p; if (p == lowDiv[j]) { int k = tmp[j]; ret[i] = ret[j] / k * (k + 1); tmp[i] = k + 1; } else { ret[i] = ret[j] * 2; tmp[i] = 2; } } return ret; } List<Integer> getDivsNotSorted(int x) { List<Integer> ret = new ArrayList<Integer>(0); ret.add(1); while (x > 1) { int sz = ret.size(); int pr = lowDiv[x]; while (lowDiv[x] == pr) { int to = ret.size(); for (int i = ret.size() - sz; i < to; i++) { ret.add(ret.get(i) * pr); } x /= pr; } } return ret; } int[] moebiusFunction() { int[] mu = new int[N + 1]; mu[1] = 1; for (int i = 2; i <= N; i++) { int p = lowDiv[i]; int j = i / p; if (p != lowDiv[j]) { mu[i] = -mu[j]; } } return mu; } int[] eulerFunction() { int[] phi = new int[N + 1]; phi[1] = 1; for (int i = 2; i <= N; i++) { int p = lowDiv[i]; int j = i / p; phi[i] = phi[j] * (p != lowDiv[j] ? p - 1 : p); } return phi; } } void preCalc() { } void stress() { } void test() { } B() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); preCalc(); submit(); //stress(); //test(); out.close(); } static final Random rng = new Random(); static int rand(int l, int r) { return l + rng.nextInt(r - l + 1); } public static void main(String[] args) throws IOException { new B(); } BufferedReader br; PrintWriter out; StringTokenizer st; String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } String nextString() { try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
a5618ca709f2f852e5fd9089c16de8a9
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int x = in.nextInt(); int y = in.nextInt(); int[] array = in.nextIntArray(n); long[] cnt = new long[2000010]; long[] sum = new long[2000010]; for (int num : array) { cnt[num]++; sum[num] += num; } for (int i = 1; i <= 2000000; i++) { cnt[i] += cnt[i - 1]; sum[i] += sum[i - 1]; } Prime prime = new Prime(1000000); List<Integer> primes = prime.getPrimes(); long ans = Long.MAX_VALUE; for (int p : primes) { long tmpSum = 0; int t = Math.min(p - 1, x / y); for (int i = p; i <= 2000000; i += p) { tmpSum += x * ArrayUtils.getSumArrayDiff(cnt, i - (p - 1), i - t - 1); tmpSum += y * (ArrayUtils.getSumArrayDiff(cnt, i - t, i - 1) * i - ArrayUtils.getSumArrayDiff(sum, i - t, i - 1)); } ans = Math.min(ans, tmpSum); } out.println(ans); } } static class InputReader { BufferedReader in; StringTokenizer tok; public String nextString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " "); } catch (IOException e) { throw new InputMismatchException(); } } return tok.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public InputReader(InputStream inputStream) { in = new BufferedReader(new InputStreamReader(inputStream)); tok = new StringTokenizer(""); } } static class Prime { int n; boolean[] isPrime; ArrayList<Integer> primes; public Prime(int n) { this.n = n; isPrime = new boolean[n + 1]; primes = new ArrayList<>(); sieve(); } private void sieve() { for (int i = 2; i <= n; i++) { if (!isPrime[i]) { primes.add(i); for (long j = (long) i * i; j <= n; j += i) { isPrime[(int) j] = true; } } } } public ArrayList<Integer> getPrimes() { return primes; } } static class ArrayUtils { public static long getSumArrayDiff(long[] sumArray, int from, int to) { return sumArray[to] - (from >= 0 ? sumArray[from - 1] : 0); } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
987a16e4cad2b3f1c83f325e7215e929
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.IOException; import java.util.InputMismatchException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int x = in.nextInt(); int y = in.nextInt(); int[] array = in.nextIntArray(n); long[] cnt = new long[2000010]; long[] sum = new long[2000010]; for (int num : array) { cnt[num]++; sum[num] += num; } for (int i = 1; i <= 2000000; i++) { cnt[i] += cnt[i - 1]; sum[i] += sum[i - 1]; } Prime prime = new Prime(1000000); List<Integer> primes = prime.getPrimes(); long ans = Long.MAX_VALUE; for (int p : primes) { long tmpSum = 0; int t = Math.min(p - 1, x / y); for (int i = p; i <= 2000000; i += p) { tmpSum += x * (cnt[i - t - 1] - cnt[i - p]); tmpSum += y * ((cnt[i - 1] - cnt[i - t - 1]) * i - (sum[i - 1] - sum[i - t - 1])); } ans = Math.min(ans, tmpSum); } out.println(ans); } } static class InputReader { BufferedReader in; StringTokenizer tok; public String nextString() { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " "); } catch (IOException e) { throw new InputMismatchException(); } } return tok.nextToken(); } public int nextInt() { return Integer.parseInt(nextString()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for (int i = 0; i < n; i++) { res[i] = nextInt(); } return res; } public InputReader(InputStream inputStream) { in = new BufferedReader(new InputStreamReader(inputStream)); tok = new StringTokenizer(""); } } static class Prime { int n; boolean[] isPrime; ArrayList<Integer> primes; public Prime(int n) { this.n = n; isPrime = new boolean[n + 1]; primes = new ArrayList<>(); sieve(); } private void sieve() { for (int i = 2; i <= n; i++) { if (!isPrime[i]) { primes.add(i); for (long j = (long) i * i; j <= n; j += i) { isPrime[(int) j] = true; } } } } public ArrayList<Integer> getPrimes() { return primes; } } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
5220b47babd677e726ccca627ec6db04
train_002.jsonl
1504535700
Arpa has found a list containing n numbers. He calls a list bad if and only if it is not empty and gcd (see notes section for more information) of numbers in the list is 1.Arpa can perform two types of operations: Choose a number and delete it with cost x. Choose a number and increase it by 1 with cost y. Arpa can apply these operations to as many numbers as he wishes, and he is allowed to apply the second operation arbitrarily many times on the same number.Help Arpa to find the minimum possible cost to make the list good.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; void work() { int n=in.nextInt(); long x=in.nextLong(),y=in.nextLong(); long[] sum=new long[2000001]; long[] sum2=new long[2000001]; for(int i=0;i<n;i++) { int a=in.nextInt(); sum[a]++; sum2[a]+=a; } int v=(int)(x/y); boolean[] rec=new boolean[1000001]; for(int i=2;i*i<=1000000;i++) { if(rec[i])continue; for(int j=i;j*i<=1000000;j++) { rec[i*j]=true; } } for(int i=1;i<=2000000;i++) { sum[i]+=sum[i-1]; sum2[i]+=sum2[i-1]; } long ret=Long.MAX_VALUE; for(int i=2;i<=1000000;i++) { if(!rec[i]) { int d=i-v-1; long c=0; for(int j=0;j<=1000000;j+=i) { if(d>0) { c+=x*(sum[j+d]-sum[j]); long e=sum[j+i]-sum[j+d]; c+=(e*(i+j)-(sum2[i+j]-sum2[j+d]))*y; }else { long e=sum[j+i]-sum[j]; c+=(e*(i+j)-(sum2[i+j]-sum2[j]))*y; } } ret=Math.min(c,ret); } } out.println(ret); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["4 23 17\n1 17 17 16", "10 6 2\n100 49 71 73 66 96 8 60 41 63"]
2 seconds
["40", "10"]
NoteIn example, number 1 must be deleted (with cost 23) and number 16 must increased by 1 (with cost 17).A gcd (greatest common divisor) of a set of numbers is the maximum integer that divides all integers in the set. Read more about gcd here.
Java 8
standard input
[ "implementation", "number theory" ]
41a1b33baa83aea57423b160247adcb6
First line contains three integers n, x and y (1 ≤ n ≤ 5·105, 1 ≤ x, y ≤ 109) — the number of elements in the list and the integers x and y. Second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106) — the elements of the list.
2,100
Print a single integer: the minimum possible cost to make the list good.
standard output
PASSED
e52bb80ddd730e8c6a6ef5eb7ab05f1d
train_002.jsonl
1304485200
Polycarp loves not only to take pictures, but also to show his photos to friends. On his personal website he has recently installed a widget that can display n photos with the scroll option. At each moment of time the widget displays exactly one photograph with the option showing the previous/next one. From the first photo, you can switch to the second one or to the n-th one, from the second photo you can switch to the third one or to the first one, etc. Thus, navigation is performed in a cycle.Polycarp's collection consists of m photo albums, the i-th album contains ai photos. Polycarp wants to choose n photos and put them on a new widget. To make watching the photos interesting to the visitors, he is going to post pictures so that no two photos from one album were neighboring (each photo will have exactly two neighbors, the first photo's neighbors are the second and the n-th one).Help Polycarp compile a photo gallery. Select n photos from his collection and put them in such order that no two photos from one album went one after the other.
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int n = readInt(); int total = readInt(); ArrayList<State> list = new ArrayList<State>(); for(int i = 1; i <= total; i++) { list.add(new State(i, readInt())); } Collections.sort(list); int[] ret = new int[n]; for(State out: list) { outer: while(out.val-- > 0) { for(int i = 0; i < n; i++) { if(ret[i] > 0) continue; if(ret[(i+1)%n] == 0 && ret[(i+n-1)%n] == 0) { ret[i] = out.index; continue outer; } } for(int i = 0; i < n; i++) { if(ret[i] > 0) continue; if(ret[(i+1)%n] == out.index || ret[(i+n-1)%n] == out.index) { continue; } if(ret[(i+1)%n] == 0 || ret[(i+n-1)%n] == 0) { ret[i] = out.index; continue outer; } } for(int i = 0; i < n; i++) { if(ret[i] > 0) continue; if(ret[(i+1)%n] == out.index || ret[(i+n-1)%n] == out.index) { continue; } ret[i] = out.index; continue outer; } } } int count = 0; for(int out: ret) { if(out == 0) { count++; } } if(count > 0) { pw.println(-1); } else { for(int out: ret) { pw.print(out + " "); } pw.println(); } } exitImmediately(); } static class State implements Comparable<State> { public int index, val; public State(int a, int b) { index = a; val = b; } public int compareTo(State s) { return val - s.val; } } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextLine() throws IOException { if(!br.ready()) { exitImmediately(); } st = null; return br.readLine(); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["4 3\n1 3 5", "10 2\n5 5", "10 3\n1 10 3"]
2 seconds
["3 1 3 2", "2 1 2 1 2 1 2 1 2 1", "-1"]
null
Java 7
standard input
[ "constructive algorithms", "greedy" ]
2e99f0b671c80da1e768fa9bc7796481
The first line contains two integers n and m (3 ≤ n ≤ 1000, 1 ≤ m ≤ 40), where n is the number of photos on the widget, and m is the number of albums. The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 1000), where ai is the number of photos in the i-th album.
2,100
Print the single number -1 if there is no solution. Otherwise, print n numbers t1, t2, ..., tn, where ti represents the number of the album of the i-th picture in the widget. The albums are numbered from 1 in the order of their appearance in the input. If there are several solutions, print any of them.
standard output
PASSED
5063ebf211446ca5307f57dd19eefcd4
train_002.jsonl
1304485200
Polycarp loves not only to take pictures, but also to show his photos to friends. On his personal website he has recently installed a widget that can display n photos with the scroll option. At each moment of time the widget displays exactly one photograph with the option showing the previous/next one. From the first photo, you can switch to the second one or to the n-th one, from the second photo you can switch to the third one or to the first one, etc. Thus, navigation is performed in a cycle.Polycarp's collection consists of m photo albums, the i-th album contains ai photos. Polycarp wants to choose n photos and put them on a new widget. To make watching the photos interesting to the visitors, he is going to post pictures so that no two photos from one album were neighboring (each photo will have exactly two neighbors, the first photo's neighbors are the second and the n-th one).Help Polycarp compile a photo gallery. Select n photos from his collection and put them in such order that no two photos from one album went one after the other.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CodeF { static class Scanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String nextLine() { try { return br.readLine(); } catch(Exception e) { throw(new RuntimeException()); } } public String next() { while(!st.hasMoreTokens()) { String l = nextLine(); if(l == null) return null; st = new StringTokenizer(l); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int[] res = new int[n]; for(int i = 0; i < res.length; i++) res[i] = nextInt(); return res; } public long[] nextLongArray(int n) { long[] res = new long[n]; for(int i = 0; i < res.length; i++) res[i] = nextLong(); return res; } public double[] nextDoubleArray(int n) { double[] res = new double[n]; for(int i = 0; i < res.length; i++) res[i] = nextDouble(); return res; } public void sortIntArray(int[] array) { Integer[] vals = new Integer[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortLongArray(long[] array) { Long[] vals = new Long[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public void sortDoubleArray(double[] array) { Double[] vals = new Double[array.length]; for(int i = 0; i < array.length; i++) vals[i] = array[i]; Arrays.sort(vals); for(int i = 0; i < array.length; i++) array[i] = vals[i]; } public String[] nextStringArray(int n) { String[] vals = new String[n]; for(int i = 0; i < n; i++) vals[i] = next(); return vals; } Integer nextInteger() { String s = next(); if(s == null) return null; return Integer.parseInt(s); } int[][] nextIntMatrix(int n, int m) { int[][] ans = new int[n][]; for(int i = 0; i < n; i++) ans[i] = nextIntArray(m); return ans; } static <T> T fill(T arreglo, int val) { if(arreglo instanceof Object[]) { Object[] a = (Object[]) arreglo; for(Object x : a) fill(x, val); } else if(arreglo instanceof int[]) Arrays.fill((int[]) arreglo, val); else if(arreglo instanceof double[]) Arrays.fill((double[]) arreglo, val); else if(arreglo instanceof long[]) Arrays.fill((long[]) arreglo, val); return arreglo; } } static int anterior(int i, int n) { if(i == 0) return n - 1; return i - 1; } static int siguiente(int i, int n) { return (i + 1) % n; } static boolean esPosibleSwap(int i, int j, int[] vals) { if(siguiente(i, vals.length) == j) return vals[i] != vals[siguiente(j, vals.length)] && vals[j] != vals[anterior(i, vals.length)]; if(vals[i] != vals[anterior(j, vals.length)] && vals[i] != vals[siguiente(j, vals.length)] && vals[j] != vals[anterior(i, vals.length)] && vals[j] != vals[siguiente(i, vals.length)]) return true; else return false; } static boolean swap(int i, int j, int[] vals) { if(!esPosibleSwap(i, j, vals)) return false; int tmp = vals[i]; vals[i] = vals[j]; vals[j] = tmp; return true; } public static void main(String[] args) { Scanner sc = new Scanner(); int n = sc.nextInt(); int m = sc.nextInt(); if(m == 1) { System.out.println(-1); return; } int[] posibles = sc.nextIntArray(m); int[] vals = new int[n]; int anterior = -1; boolean paila = false; for(int i = 0; i < vals.length; i++) { int maximo = -1; int cual = -1; for(int j = 0; j < posibles.length; j++) { if(posibles[j] > maximo && posibles[j] > 0 && anterior != j) { maximo = posibles[j]; cual = j; } } if(maximo == -1) { paila = true; break; } vals[i] = cual; posibles[cual]--; anterior = cual; } if(vals[0] == vals[vals.length - 1]) { int cual = -1; for(int j = 0; j < posibles.length; j++) { if(posibles[j] > 0 && j != vals[vals.length - 2] && j != vals[0]) { cual = j; break; } } if(cual == -1) { int cuenta = 0; while(cual == -1 && cuenta < 100) { if(isOk(vals)) { cual = 0; break; } for(int i = 0; i < vals.length - 1; i++) { if(swap(i, vals.length - 1, vals)) break; } if(cual != -1) break; outer: for(int i = 0; i < vals.length - 1; i++) { for(int j = i + 1; j < vals.length - 1; j++) { if(swap(i, j, vals)) break outer; } } cuenta++; } if(cual == -1) paila = true; } else vals[vals.length - 1] = cual; } if(paila) { System.out.println(-1); return; } boolean empezo = false; for(int i = 0; i < n; i++) { if(i != 0) System.out.print(" "); System.out.print(vals[i] + 1); } System.out.println(); } private static boolean isOk(int[] vals) { for(int i = 0; i < vals.length; i++) { if(vals[i] == vals[anterior(i, vals.length)]) return false; if(vals[i] == vals[siguiente(i, vals.length)]) return false; } return true; } }
Java
["4 3\n1 3 5", "10 2\n5 5", "10 3\n1 10 3"]
2 seconds
["3 1 3 2", "2 1 2 1 2 1 2 1 2 1", "-1"]
null
Java 7
standard input
[ "constructive algorithms", "greedy" ]
2e99f0b671c80da1e768fa9bc7796481
The first line contains two integers n and m (3 ≤ n ≤ 1000, 1 ≤ m ≤ 40), where n is the number of photos on the widget, and m is the number of albums. The second line contains m integers a1, a2, ..., am (1 ≤ ai ≤ 1000), where ai is the number of photos in the i-th album.
2,100
Print the single number -1 if there is no solution. Otherwise, print n numbers t1, t2, ..., tn, where ti represents the number of the album of the i-th picture in the widget. The albums are numbered from 1 in the order of their appearance in the input. If there are several solutions, print any of them.
standard output
PASSED
af2228418f64f3c3a3f3bbad34abaf33
train_002.jsonl
1304485200
Polycarp is very careful. He even types numeric sequences carefully, unlike his classmates. If he sees a sequence without a space after the comma, with two spaces in a row, or when something else does not look neat, he rushes to correct it. For example, number sequence written like "1,2 ,3,...,   10" will be corrected to "1, 2, 3, ..., 10".In this task you are given a string s, which is composed by a concatination of terms, each of which may be: a positive integer of an arbitrary length (leading zeroes are not allowed), a "comma" symbol (","), a "space" symbol (" "), "three dots" ("...", that is, exactly three points written one after another, also known as suspension points). Polycarp wants to add and remove spaces in the string s to ensure the following: each comma is followed by exactly one space (if the comma is the last character in the string, this rule does not apply to it), each "three dots" term is preceded by exactly one space (if the dots are at the beginning of the string, this rule does not apply to the term), if two consecutive numbers were separated by spaces only (one or more), then exactly one of them should be left, there should not be other spaces. Automate Polycarp's work and write a program that will process the given string s.
256 megabytes
// practice with kaiboy import java.io.*; import java.util.*; public class CF81B extends PrintWriter { CF81B() { super(System.out, true); } Scanner sc = new Scanner(System.in); public static void main(String[] $) { CF81B o = new CF81B(); o.main(); o.flush(); } void main() { byte[] aa = sc.nextLine().getBytes(); int n = aa.length; int m = n + n; byte[] bb = new byte[m]; m = 0; for (int i = 0; i < n; i++) { byte a = aa[i]; if (a == ',') { if (m >= 2 && bb[m - 2] != ',' && bb[m - 1] == ' ') m--; bb[m++] = ','; bb[m++] = ' '; } else if (a == '.') { if (m > 0 && bb[m - 1] != ' ') bb[m++] = ' '; bb[m++] = '.'; bb[m++] = '.'; bb[m++] = '.'; i += 2; } else if (a == ' ') { if (m > 0 && bb[m - 1] != ' ') bb[m++] = ' '; } else { if (m >= 2 && bb[m - 2] == '.' && bb[m - 1] == ' ') m--; bb[m++] = a; } } if (m > 0 && bb[m - 1] == ' ') m--; println(new String(bb, 0, m)); } }
Java
["1,2 ,3,..., 10", "1,,,4...5......6", "...,1,2,3,..."]
2 seconds
["1, 2, 3, ..., 10", "1, , , 4 ...5 ... ...6", "..., 1, 2, 3, ..."]
null
Java 11
standard input
[ "implementation", "strings" ]
c7d8c71a1f7e6c7364cce5bddd488a2f
The input data contains a single string s. Its length is from 1 to 255 characters. The string s does not begin and end with a space. Its content matches the description given above.
1,700
Print the string s after it is processed. Your program's output should be exactly the same as the expected answer. It is permissible to end output line with a line-break character, and without it.
standard output
PASSED
1635588b42b471890068c8107aae661c
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = in.nextIntArray(n); int[] b = in.nextIntArray(n); int[] c = in.nextIntArray(n); long[][] dp = new long[2][n]; dp[0][n - 1] = a[n - 1]; dp[1][n - 1] = b[n - 1]; for (int i = n - 2; i >= 0; i--) { dp[0][i] = Math.max(a[i] + dp[1][i + 1], b[i] + dp[0][i + 1]); dp[1][i] = Math.max(b[i] + dp[1][i + 1], c[i] + dp[0][i + 1]); } out.println(dp[0][0]); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[16384]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
5dc0ffc7640ae7594f995077372eb823
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
/** * DA-IICT * Author : PARTH PATEL */ import java.io.*; import java.math.*; import java.util.*; import static java.util.Arrays.fill; import static java.lang.Math.*; import static java.util.Arrays.sort; import static java.util.Collections.sort; public class D358 { public static int mod = 1000000007; static FasterScanner in = new FasterScanner(); static PrintWriter out = new PrintWriter(System.out); static int n; static int[] a; static int[] b; static int[] c; static int[][] dp; public static int func(int index,int previouseaten) { //previouseaten==1 YES //previouseaten==0 NO if(index>n) { return 0; } if(dp[index][previouseaten]!=-1) { return dp[index][previouseaten]; } if(index==n && previouseaten==0) { return a[index]; } if(index==n && previouseaten==1) { return b[index]; } if(previouseaten==1) { //previoushare has eaten int result1=func(index+1, 1)+b[index]; int result2=func(index+1, 0)+c[index]; return dp[index][previouseaten]=max(result1, result2); } if(previouseaten==0) { //previoushare has not eaten int result1=func(index+1, 1)+a[index]; int result2=func(index+1, 0)+b[index]; return dp[index][previouseaten]=max(result1, result2); } return dp[index][previouseaten]; } public static void main(String[] args) { n=in.nextInt(); a=new int[n+1]; b=new int[n+1]; c=new int[n+1]; for(int i=1;i<=n;i++) { a[i]=in.nextInt(); } for(int i=1;i<=n;i++) { b[i]=in.nextInt(); } for(int i=1;i<=n;i++) { c[i]=in.nextInt(); } dp=new int[n+1][2]; for(int i=0;i<=n;i++) { dp[i][0]=-1; dp[i][1]=-1; } out.println(func(1, 0)); out.close(); } public static long pow(long x, long n, long mod) { long res = 1; for (long p = x; n > 0; n >>= 1, p = (p * p) % mod) { if ((n & 1) != 0) { res = (res * p % mod); } } return res; } public static long gcd(long n1, long n2) { long r; while (n2 != 0) { r = n1 % n2; n1 = n2; n2 = r; } return n1; } public static long lcm(long n1, long n2) { long answer = (n1 * n2) / (gcd(n1, n2)); return answer; } static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int snumChars; public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
302c89717f3366e65bdc9d80b68a618e
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.*; import java.util.stream.Stream; public class Main implements Runnable { static final int MOD = (int) 1e9 + 7; static final int MI = (int) 1e9; static final long ML = (long) 1e18; static final Reader in = new Reader(); static final PrintWriter out = new PrintWriter(System.out); StringBuilder answer = new StringBuilder(); public static void main(String[] args) { new Thread(null, new Main(), "persefone", 1 << 32).start(); } @Override public void run() { solve(); printf(); flush(); } void solve() { n = in.nextInt(); a = new int[n + 1]; b = new int[n + 1]; c = new int[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextInt(); } for (int i = 1; i <= n; i++) { b[i] = in.nextInt(); } for (int i = 1; i <= n; i++) { c[i] = in.nextInt(); } dp = new int[n + 1][2]; for (int i = 1; i <= n; i++) { Arrays.fill(dp[i], -1); } printf(calc(1, 0)); } private int n; private int[] a, b, c; private int[][] dp; int calc(int position, int before) { if (position == n) { return dp[position][before] = before == 1 ? b[position] : a[position]; } if (dp[position][before] != -1) return dp[position][before]; int feed = (before == 1 ? b[position] : a[position]) + calc(position + 1, 1); int nofeed = (before == 1 ? c[position] : b[position]) + calc(position + 1, 0); return dp[position][before] = Math.max(feed, nofeed); } void printf() { out.print(answer); } void close() { out.close(); } void flush() { out.flush(); } void printf(Stream<?> str) { str.forEach(o -> add(o, " ")); add("\n"); } void printf(Object... obj) { printf(false, obj); } void printfWithDescription(Object... obj) { printf(true, obj); } private void printf(boolean b, Object... obj) { if (obj.length > 1) { for (int i = 0; i < obj.length; i++) { if (b) add(obj[i].getClass().getSimpleName(), " - "); if (obj[i] instanceof Collection<?>) { printf((Collection<?>) obj[i]); } else if (obj[i] instanceof int[][]) { printf((int[][]) obj[i]); } else if (obj[i] instanceof long[][]) { printf((long[][]) obj[i]); } else if (obj[i] instanceof double[][]) { printf((double[][]) obj[i]); } else printf(obj[i]); } return; } if (b) add(obj[0].getClass().getSimpleName(), " - "); printf(obj[0]); } void printf(Object o) { if (o instanceof int[]) printf(Arrays.stream((int[]) o).boxed()); else if (o instanceof char[]) printf(new String((char[]) o)); else if (o instanceof long[]) printf(Arrays.stream((long[]) o).boxed()); else if (o instanceof double[]) printf(Arrays.stream((double[]) o).boxed()); else if (o instanceof boolean[]) { for (boolean b : (boolean[]) o) add(b, " "); add("\n"); } else add(o, "\n"); } void printf(int[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(long[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(double[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(boolean[]... obj) { for (int i = 0; i < obj.length; i++) printf(obj[i]); } void printf(Collection<?> col) { printf(col.stream()); } <T, K> void add(T t, K k) { if (t instanceof Collection<?>) { ((Collection<?>) t).forEach(i -> add(i, " ")); } else if (t instanceof Object[]) { Arrays.stream((Object[]) t).forEach(i -> add(i, " ")); } else add(t); add(k); } <T> void add(T t) { answer.append(t); } static class Reader { private BufferedReader br; private StringTokenizer st; Reader() { br = new BufferedReader(new InputStreamReader(System.in)); } Reader(String fileName) throws FileNotFoundException { br = new BufferedReader(new FileReader(fileName)); } boolean isReady() throws IOException { return br.ready(); } String next() { try { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String s = ""; try { s = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
649a1b2d99d5c8c0781ab93b5bf487d6
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.*; public class D { static StringBuilder st = new StringBuilder(); static int [] a ; static int [] b ; static int [] c; static long memo [][] ; static int n ; static long dp(int idx , int lst) { if(idx == n) return 0 ; if(memo[lst][idx] != -1)return memo[lst][idx] ; long ans = -(1l << 61) ; if(idx == n - 1) { if(lst == 0 ) ans = Math.max(ans, (a[idx] + dp(idx + 1, 0) )) ; else ans = Math.max(ans, (b[idx] + dp(idx + 1, 1 ))) ; } else if(idx == 0) { ans = Math.max(ans, Math.max(a[idx] + dp(idx + 1, 1) , b[idx] + dp(idx + 1, 0))) ; } else { if(lst == 0 ) ans = Math.max(ans, Math.max(a[idx] + dp(idx + 1, 1) , b[idx] + dp(idx + 1, 0))) ; else ans = Math.max(ans, Math.max(b[idx] + dp(idx + 1, 1) , c[idx] + dp(idx + 1, 0 ))) ; } return memo[lst][idx] = ans ; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt() ; a = new int [n] ; b = new int [n] ; c = new int [n] ; for(int i = 0 ; i < n ;i++) a[i] = sc.nextInt() ; for(int i = 0 ; i < n ;i++) b[i] = sc.nextInt() ; for(int i = 0 ; i < n ;i++) c[i] = sc.nextInt() ; memo = new long [2][n] ; for(int i = 0 ; i < 2 ; i++)Arrays.fill(memo[i], -1); out.println(dp(0, 0)); out.flush(); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream in) { br = new BufferedReader(new InputStreamReader(System.in)); } String next() throws Exception { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws Exception { return Integer.parseInt(next()); } long nextLong() throws Exception { return Long.parseLong(next()); } double nextDouble() throws Exception { return Double.parseDouble(next()); } } static void shuffle(int[] a) { int n = a.length; for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
3ef1a42b76725ad5fae553c020a6f760
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.StringTokenizer; public class l057 { public static void main(String[] args) throws Exception { // StringTokenizer stok = new StringTokenizer(new Scanner(new File("F:/books/input.txt")).useDelimiter("\\A").next()); StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next()); StringBuilder sb = new StringBuilder(); Integer n = Integer.parseInt(stok.nextToken()); long[][] a = new long[3][n]; for(int i=0;i<3;i++) { for(int j=0;j<n;j++) { a[i][j] = Long.parseLong(stok.nextToken()); } } long[][] dp = new long[4][n]; dp[0b00][0] = a[0][0]; dp[0b01][0] = a[1][0]; for(int i=1;i<n;i++) { dp[0b00][i] = Math.max(dp[0b01][i-1], dp[0b11][i-1]) + a[0][i]; dp[0b01][i] = Math.max(dp[0b01][i-1], dp[0b11][i-1]) + a[1][i]; dp[0b10][i] = Math.max(dp[0b00][i-1], dp[0b10][i-1]) + a[1][i]; dp[0b11][i] = Math.max(dp[0b00][i-1], dp[0b10][i-1]) + a[2][i]; } System.out.println(Math.max(dp[0b10][n-1], dp[0b00][n-1])); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
0991a62a7ee37dd4043c54caf164d3b8
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class DimaAndHares { static int[][] dp; static int[] a,b,c; static int n; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n]; b = new int[n]; c = new int[n]; for (int i = 0; i < a.length; i++) a[i] = sc.nextInt(); for (int i = 0; i < b.length; i++) b[i] = sc.nextInt(); for (int i = 0; i < c.length; i++) c[i] = sc.nextInt(); dp = new int[n+5][2]; for (int i = 0; i < dp.length; i++) Arrays.fill(dp[i], -1); System.out.println(solve(0, 0)); } static int solve(int ind, int prev) { if(ind == n-1) if(prev == 0) return a[ind]; else return b[ind]; int max = 0; if(dp[ind][prev] != -1) return dp[ind][prev]; if(prev == 0) max = Math.max(a[ind] + solve(ind+1, 1), b[ind] + solve(ind+1, 0)); else max = Math.max(b[ind] + solve(ind+1, 1), c[ind] + solve(ind+1, 0)); return dp[ind][prev] = max; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
8708030816be42ead4c4196a45587b23
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class D358{ void solve() { int n = ni(); int[][] v = new int[3][]; for(int i=0;i<3;i++) v[i] = ia(n); long[][] dp = new long[2][n]; Arrays.fill(dp[0], -1); Arrays.fill(dp[1], -1); out.println(recurse(0, dp, false, v)); } long recurse(int pos, long[][] dp, boolean fed, int[][] v) { int t = (fed ? 1 : 0); if(dp[t][pos] != -1) return dp[t][pos]; if(pos == dp[0].length - 1) return dp[t][pos] = v[t][pos]; long ans1, ans2; if(fed) { ans1 = recurse(pos+1, dp, false, v) + v[2][pos]; ans2 = recurse(pos+1, dp, true, v) + v[1][pos]; } else { ans1 = recurse(pos+1, dp, false, v) + v[1][pos]; ans2 = recurse(pos+1, dp, true, v) + v[0][pos]; } return dp[t][pos] = Math.max(ans1, ans2); } public static void main(String[] args){new D358().run();} private byte[] bufferArray = new byte[1024]; private int bufLength = 0; private int bufCurrent = 0; InputStream inputStream; PrintWriter out; public void run() { inputStream = System.in; out = new PrintWriter(System.out); solve(); out.flush(); } int nextByte() { if(bufLength==-1) throw new InputMismatchException(); if(bufCurrent>=bufLength) { bufCurrent = 0; try {bufLength = inputStream.read(bufferArray);} catch(IOException e) { throw new InputMismatchException();} if(bufLength<=0) return -1; } return bufferArray[bufCurrent++]; } boolean isSpaceChar(int x) {return (x<33 || x>126);} boolean isDigit(int x) {return (x>='0' && x<='9');} int nextNonSpace() { int x; while((x=nextByte())!=-1 && isSpaceChar(x)); return x; } int ni() { long ans = nl(); if ( Integer.MIN_VALUE <= ans && ans <= Integer.MAX_VALUE ) return (int)ans; throw new InputMismatchException(); } long nl() { long ans = 0; boolean neg = false; int x = nextNonSpace(); if(x=='-') { neg = true; x = nextByte(); } while(!isSpaceChar(x)) { if(isDigit(x)) { ans = ans*10 + x -'0'; x = nextByte(); } else throw new InputMismatchException(); } return neg ? -ans:ans; } String ns() { StringBuilder sb = new StringBuilder(); int x = nextNonSpace(); while(!isSpaceChar(x)) { sb.append((char)x); x = nextByte(); } return sb.toString(); } char nc() { return (char)nextNonSpace();} double nd() { return (double)Double.parseDouble(ns()); } char[] ca() { return ns().toCharArray();} char[] ca(int n) { char[] ans = new char[n]; int p =0; int x = nextNonSpace(); while(p<n) { ans[p++] = (char)x; x = nextByte(); } return ans; } int[] ia(int n) { int[] ans = new int[n]; for(int i=0;i<n;i++) ans[i]=ni(); return ans; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
4638fbec164f263ec9914b7e36f88daa
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static int N; public static int[] a, b, c; public static int[][] dp; public static void main(String[] args) throws IOException { BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(f.readLine()); a = new int[N]; b = new int[N]; c = new int[N]; StringTokenizer st = new StringTokenizer(f.readLine()); for (int i = 0; i < N; i++) { a[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(f.readLine()); for (int i = 0; i < N; i++) { b[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(f.readLine()); for (int i = 0; i < N; i++) { c[i] = Integer.parseInt(st.nextToken()); } dp = new int[N + 1][2]; dp[0][0] = -1 << 29; for (int i = 1; i <= N; i++) { dp[i][1] = Math.max(dp[i - 1][1] + b[i - 1], dp[i - 1][0] + c[i - 1]); dp[i][0] = Math.max(dp[i - 1][1] + a[i - 1], dp[i - 1][0] + b[i - 1]); } System.out.println(dp[N][0]); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
befec15799307b67d1562aafbdbf30a6
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Stack; public class MaxFlow { static int[] hungry = new int[3001]; static int[] one = new int[ 3001]; static int[] full = new int[3001]; static int[][] dp = new int[3001][2]; static int n; static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); //BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); n = in.nextInt(); for(int i=0; i<n; i++) { hungry[i] = in.nextInt(); } for(int i=0; i<n; i++) { one[i] = in.nextInt(); } for(int i=0; i<n; i++) { full[i] = in.nextInt(); } for(int i=0; i<dp.length; i++) { for(int j=0; j<dp[i].length; j++) { dp[i][j] = -1; } } System.out.println(rec(1, 0)); } private static int rec(int i, int prev) { if(i == n) { // prev ate before prev if(prev == 0) { return hungry[i-1]; } // prev ate after else { return one[i-1]; } } else if(i == 1) { int best = 0; // we eat before prev best = one[i-1] + rec(i+1, 0); // we eat after prev best = Math.max(best, hungry[i-1] + rec(i+1, 1)); return best; } else if(dp[i][prev] != -1) { return dp[i][prev]; } else { int best = 0; if(prev == 0) { // prev ate before prev prev // we ate after best = hungry[i-1] + rec(i+1, 1); // prev ate before prev prev // we are before prev best = Math.max(best, one[i-1] + rec(i+1, 0)); } else if(prev == 1) { // prev ate after prev prev // we eat after prev best = one[i-1] + rec(i+1, 1); // prev ate after prev prev // we beofore prev best = Math.max(best, full[i-1] + rec(i+1, 0)); } return dp[i][prev] = best; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
5589ae7c40adc89c2958974ebe9746b7
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
//package CF; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class A { static int[] a, b, c, memo[]; static int dp(int idx, int last){ if(idx == a.length-1){ return last == 0?a[idx]:b[idx]; } if(memo[idx][last] != -1) return memo[idx][last]; int ans = 0; if(last == 0){ ans = Math.max(a[idx] + dp(idx+1, 1), b[idx] + dp(idx+1, 0)); } else{ ans = Math.max(b[idx] + dp(idx+1, 1), c[idx] + dp(idx+1, 0)); } return memo[idx][last] = ans; } public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); a = new int[n]; b = new int[n]; c = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = sc.nextInt(); } for (int i = 0; i < a.length; i++) { b[i] = sc.nextInt(); } for (int i = 0; i < a.length; i++) { c[i] = sc.nextInt(); } memo = new int[n+1][2]; for(int [] i:memo) Arrays.fill(i, -1); out.println(dp(0, 0)); out.flush(); out.close(); } static class Scanner { BufferedReader bf; StringTokenizer st; public Scanner(InputStream i) { bf = new BufferedReader(new InputStreamReader(i)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(bf.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
5c597d585823ef4068408386ba3e76ef
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashSet; import java.util.InputMismatchException; import java.util.LinkedList; public class Solution123 implements Runnable { static final int MAX = 1000000007; static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Solution123(),"Solution123",1<<26).start(); } static long[] ans = new long[1000001]; static int[] temp; static long[][] count = new long[1000001][9]; static int[] freq; static HashSet<Integer> pw2 = new HashSet(); static ArrayList<Integer> ar[] = new ArrayList[9]; public void run() { InputReader sc= new InputReader(System.in); PrintWriter w= new PrintWriter(System.out); int n = sc.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; int[] dp0 = new int[n+1]; int[] dp1 = new int[n+1]; for(int i = 0;i < n;i++){ a[i] = sc.nextInt(); } for(int i = 0;i < n;i++){ b[i] = sc.nextInt(); } for(int i = 0;i < n;i++){ c[i] = sc.nextInt(); } dp0[n] = a[n-1]; dp1[n] = b[n-1]; for(int i = n-1;i > 0;i--){ dp0[i] = Math.max(dp0[i+1] + b[i-1],dp1[i+1] + a[i-1]); dp1[i] = Math.max(dp0[i+1] + c[i-1],dp1[i+1] + b[i-1]); } w.println(dp0[1]); w.close(); } static void fun(){ ans[1] = 2; for(int i = 2;i <= ans.length-1;i++){ ans[i] = (ans[i-1] % MAX + ans[i-1] % MAX - (i/2) + ((i % 2 == 0) ? dpe[(i-2)/2]%MAX : dpo[(i-2)/2]%MAX))%MAX; } } static long[] num = new long[1000001]; static long[] dpo = new long[500001]; static long[] dpe = new long[500001]; static void power(){ dpe[0] = 0; for(int i = 1;i < num.length;i++){ num[i] = i-1; if(i == 1){ dpo[0] = (num[i]); }else if(i == 2){ dpe[1] = num[i]; }else if(i % 2 != 0){ dpo[i/2] = dpo[i/2-1] + num[i]; }else{ dpe[i/2] = dpe[i/2-1] + num[i]; } } } static class Pair{ int a; int b; int c; Pair(int a,int b,int c){ this.a = a; this.b = b; this.c = c; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
85909e9aa4f6b42ac24099c7b15e6b52
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.awt.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; import java.util.List; public class Main { static int mod = (int) 1e9 + 7; static int[] a,b,c; static int[][] dp; static int n; public static void main(String[] args) { FastReader sc = new FastReader(); n=sc.nextInt(); a=new int[n];b=new int[n];c=new int[n]; dp=new int[2][n]; for(int i=0;i<n;i++)a[i]=sc.nextInt(); for(int i=0;i<n;i++)b[i]=sc.nextInt(); for(int i=0;i<n;i++)c[i]=sc.nextInt(); for(int[] i:dp)Arrays.fill(i,-1); System.out.println(solve(0,0)); } static int solve(int position,int state){ if(position==n-1){ if(state==0)return a[position]; else return b[position]; } if(dp[state][position]!=-1)return dp[state][position]; int res=0; if(state==0)res+=Math.max(solve(position+1,1)+a[position],solve(position+1,0)+b[position]); else res+=Math.max(solve(position+1,1)+b[position],solve(position+1,0)+c[position]); return dp[state][position]=res; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
c42dbf78b27c77812bc6f899cc9312f3
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.*; public class AA { public static void main(String[] args)throws Throwable { MyScanner sc=new MyScanner(); PrintWriter pw=new PrintWriter(System.out); n=sc.nextInt(); a=new int [n]; b=new int [n]; c=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); for(int i=0;i<n;i++) b[i]=sc.nextInt(); for(int i=0;i<n;i++) c[i]=sc.nextInt(); mem=new int [n][2]; for(int [] x : mem) Arrays.fill(x, -1); pw.println(dp(0, 0)); pw.flush(); pw.close(); } static int n; static int [] a,b,c; static int [][] mem; static int dp(int i,int j){ if(i==n-1) return j==0? a[i] : b[i]; if(mem[i][j]!=-1) return mem[i][j]; int ans=0; if(j==0) ans=Math.max(b[i]+dp(i+1, 0), a[i]+dp(i+1, 1)); else ans=Math.max(c[i]+dp(i+1, 0), b[i]+dp(i+1, 1)); return mem[i][j]=ans; } static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() {while (st == null || !st.hasMoreElements()) { try {st = new StringTokenizer(br.readLine());} catch (IOException e) {e.printStackTrace();}} return st.nextToken();} int nextInt() {return Integer.parseInt(next());} long nextLong() {return Long.parseLong(next());} double nextDouble() {return Double.parseDouble(next());} String nextLine(){String str = ""; try {str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
d7e6e8949cae070d9adc2a22b69cf3e6
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException{ BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new PrintStream(System.out)); int n=Integer.parseInt(f.readLine()); a=new int[n]; b=new int[n]; c=new int[n]; StringTokenizer st=new StringTokenizer(f.readLine()); for(int i=0;i<n;i++){ a[i]=Integer.parseInt(st.nextToken()); } st=new StringTokenizer(f.readLine()); for(int i=0;i<n;i++){ b[i]=Integer.parseInt(st.nextToken()); } st=new StringTokenizer(f.readLine()); for(int i=0;i<n;i++){ c[i]=Integer.parseInt(st.nextToken()); } for(int i=0;i<n;i++){ Arrays.fill(dp[i],-1); } int ans=recurse(0,0); System.out.print(ans); f.close(); out.close(); } static int a[]; static int[]b; static int[]c; static int[][]dp=new int[3500][2]; static int recurse(int curr, int last){ int max=0; if(dp[curr][last]!=-1)return dp[curr][last]; if(curr==a.length-1)return last==0?a[curr]:b[curr]; if(last==0) { max=Math.max(max,recurse(curr+1,0)+b[curr]); max=Math.max(max,recurse(curr+1,1)+a[curr]); } else{ max=Math.max(max,recurse(curr+1,0)+c[curr]); max=Math.max(max,recurse(curr+1,1)+b[curr]); } dp[curr][last]=max; return max; } } class pair implements Comparable <pair>{ int num; int idx; public int compareTo(pair other){ return num- other.num; } pair(int a, int b) { num=a; idx=b; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
fdd94a418c3460ce2d2a67bc03e1b1db
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.*; public class Main{ InputStream is; static PrintWriter out; String INPUT = ""; static long mod = (long)1e9+7L; int n; int[] a, b, c, dp1, dp2; public void solve(){ n = ni(); a = na(n); b = na(n); c = na(n); dp1 = new int[n]; dp2 = new int[n]; Arrays.fill(dp1, -1); Arrays.fill(dp2, -1); out.println(f1(0)); } int f1(int idx){ if(dp1[idx] != -1)return dp1[idx]; if(idx == n-1)return dp1[idx] = a[idx]; return dp1[idx] = Math.max(a[idx]+f2(idx+1), b[idx]+f1(idx+1)); } int f2(int idx){ if(dp2[idx] != -1)return dp2[idx]; if(idx == n-1)return dp2[idx] = b[idx]; return dp2[idx] = Math.max(b[idx]+f2(idx+1), c[idx]+f1(idx+1)); } void run(){ is = new DataInputStream(System.in); out = new PrintWriter(System.out); int t=1;while(t-->0)solve(); out.flush(); } public static void main(String[] args)throws Exception{new Main().run();} long mod(long v, long m){if(v<0){long q=(Math.abs(v)+m-1L)/m;v=v+q*m;}return v%m;} long mod(long v){if(v<0){long q=(Math.abs(v)+mod-1L)/mod;v=v+q*mod;}return v%mod;} //Fast I/O code is copied from uwi code. private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte(){ if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns(){ int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n){ char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m){ char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n){ int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni(){ int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl(){ long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } static int i(long x){return (int)Math.round(x);} static class Pair implements Comparable<Pair>{ long fs,sc; Pair(long a,long b){ fs=a;sc=b; } public int compareTo(Pair p){ if(this.fs>p.fs)return 1; else if(this.fs<p.fs)return -1; else{ return i(this.sc-p.sc); } //return i(this.sc-p.sc); } public String toString(){ return "("+fs+","+sc+")"; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
7d3b8b7e065e1d596e0cec351c50c6df
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); D358 solver = new D358(); solver.solve(1, in, out); out.close(); } static class D358 { int oo = 987654321; int n; Hare[] hares; int[][] memo; int dp(boolean curIsBefore, int ind) { if (ind >= n) return curIsBefore ? -oo : 0; if (ind == n - 1) { if (curIsBefore) return hares[ind].zero; else return hares[ind].one; } if (memo[curIsBefore ? 1 : 0][ind] != -1) return memo[curIsBefore ? 1 : 0][ind]; int ans = 0; if (curIsBefore) { ans = Math.max(ans, hares[ind].zero + dp(false, ind + 1)); ans = Math.max(ans, hares[ind].one + dp(true, ind + 1)); } else { ans = Math.max(ans, hares[ind].one + dp(false, ind + 1)); ans = Math.max(ans, hares[ind].two + dp(true, ind + 1)); } return memo[curIsBefore ? 1 : 0][ind] = ans; } public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.nextInt(); hares = new Hare[n]; for (int i = 0; i < n; ++i) hares[i] = new Hare(); for (int i = 0; i < n; ++i) hares[i].zero = in.nextInt(); for (int i = 0; i < n; ++i) hares[i].one = in.nextInt(); for (int i = 0; i < n; ++i) hares[i].two = in.nextInt(); memo = new int[2][n]; for (int i = 0; i < 2; ++i) Arrays.fill(memo[i], -1); int ans = Math.max(hares[0].zero + dp(false, 1), hares[0].one + dp(true, 1)); out.println(ans); } class Hare { int zero; int one; int two; } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
1e7c9d5ff3f182e2b40632c71b81a687
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Abhas Jain */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int[][] dp = new int[3001][2]; int[] a; int[] b; int[] c; int n; public void solve(int testNumber, InputReader in, PrintWriter out) { n = in.ni(); for (int i = 0; i < 3001; ++i) { for (int j = 0; j < 2; ++j) dp[i][j] = -1; } a = new int[n]; b = new int[n]; c = new int[n]; for (int i = 0; i < n; ++i) a[i] = in.ni(); for (int i = 0; i < n; ++i) b[i] = in.ni(); for (int i = 0; i < n; ++i) c[i] = in.ni(); out.print(solv(0, 0)); } public int solv(int pos, int prev) { if (pos == n - 1) { if (prev == 0) return a[pos]; else return b[pos]; } if (dp[pos][prev] != -1) return dp[pos][prev]; int res1 = 0, res2 = 0; if (prev == 0) { res1 = solv(pos + 1, 1) + a[pos]; res2 = solv(pos + 1, 0) + b[pos]; } else { res1 = solv(pos + 1, 0) + c[pos]; res2 = solv(pos + 1, 1) + b[pos]; } dp[pos][prev] = Math.max(res1, res2); return dp[pos][prev]; } } 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 ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } 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
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
3ff76ad0f616affb45b77e18eb7448fd
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class CF358D { static int[] not, half, full; static int n; static int[][] mem; public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); n = sc.nextInt(); not = new int[n]; half = new int[n]; full = new int[n]; for (int i = 0; i < n; i++) { not[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { half[i] = sc.nextInt(); } for (int i = 0; i < n; i++) { full[i] = sc.nextInt(); } if(n == 1){ System.out.println(not[0]); return; } mem = new int[n][2]; for (int i = 0; i < n; i++) { Arrays.fill(mem[i], -1); } // 0 ana kalt 2ablak // 1 enta kalt 2ably System.out.println(Math.max(not[0] + dp(1, 0), half[0] + dp(1, 1))); } private static int dp(int i, int prevState) { if (i == n - 1) { if (prevState == 0) return half[i]; return not[i]; } if (mem[i][prevState] != -1) return mem[i][prevState]; int val = 0; if(prevState == 0){ val = Math.max(half[i] + dp(i+1, 0), full[i] + dp(i+1, 1)); }else{ val = Math.max(not[i] + dp(i+1, 0), half[i] + dp(i+1, 1)); } return mem[i][prevState] = val; } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public MyScanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { 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
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
87b954f7108f107effded5dab0b188b8
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } for (int i = 0; i < n; i++) { b[i] = in.nextInt(); } for (int i = 0; i < n; i++) { c[i] = in.nextInt(); } int[] d0 = new int[n]; int[] d1 = new int[n]; d0[n - 1] = a[n - 1]; d1[n - 1] = b[n - 1]; for (int i = n - 2; i >= 0; i--) { d0[i] = Math.max(a[i] + d1[i + 1], b[i] + d0[i + 1]); d1[i] = Math.max(b[i] + d1[i + 1], c[i] + d0[i + 1]); } out.println(d0[0]); } } static class InputReader { StringTokenizer st; BufferedReader br; public InputReader(InputStream is) { BufferedReader br = new BufferedReader(new InputStreamReader(is)); this.br = br; } public String next() { if (st == null || !st.hasMoreTokens()) { String nextLine = null; try { nextLine = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (nextLine == null) return null; st = new StringTokenizer(nextLine); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
943ff2053828a07605df8eb50321453d
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
//package a2oj; import java.util.*; public class DimaAndHares { static int n; static int[][] a; static int[][] dp; public static void main(String[] args) { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n][3]; dp = new int[n][2]; for(int j = 0; j < 3; j++) for(int i = 0; i < n; i++) a[i][j] = sc.nextInt(); for(int i = 0; i < n; i++) for(int j = 0; j < 2; j++) dp[i][j] = -1; System.out.println(dp(0,0)); sc.close(); } static int dp(int i, int j){ if(dp[i][j] != -1) return dp[i][j]; if(i == n - 1) return dp[i][j] = a[i][j]; return dp[i][j] = Math.max(a[i][j] + dp(i + 1, 1), a[i][j + 1] + dp(i + 1, 0)); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
2d43b7ae22e1f4f1e50939efec287b96
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
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][3]; for(int j=0;j<3;j++) for(int i=0;i<n;i++) a[i][j]=sc.nextInt(); int [][]dp=new int [n+1][2]; for(int idx=n-1;idx>=0;idx--) for(int before=0;before<=1;before++) for(int nxt=0;nxt<=1;nxt++) dp[idx][before]=Math.max(dp[idx+1][nxt]+a[idx][(idx==0?0:before)+(idx==n-1?0:(1^nxt))], dp[idx][before]); out.println(dp[0][0]); 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()); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
218ea7c238d6a4edceda813578ac1eaa
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { long MOD = 1000000007L; public class Obj implements Comparable<Obj>{ public int t; public int h; public Obj(int t_, int h_){ t = t_; h = h_; } public int compareTo(Obj other){ return t - other.t; } } public static void main (String[] args) throws java.lang.Exception { // your code goes here Codechef cf = new Codechef(); cf.Solve(); } int[][] tree; int[] lazy; long[] fac; public int GCD(int a, int b){ while (b > 0){ int tmp = b; b = a % b; a = tmp; } return a; } public void Solve(){ MyScanner sc = new MyScanner(); int n = sc.nextInt(); int[] arr = new int[n+1]; int[] brr = new int[n+1]; int[] crr = new int[n+1]; for (int i = 1; i <= n; ++i){ arr[i] = sc.nextInt(); } for (int i = 1; i <= n; ++i){ brr[i] = sc.nextInt(); } for (int i = 1; i <= n; ++i){ crr[i] = sc.nextInt(); } int[] dp0 = new int[n+1]; int[] dp1 = new int[n+1]; dp0[n] = arr[n]; dp1[n] = brr[n]; for (int i = n - 1; i > 0; --i){ if (i > 1){ dp1[i] = Math.max(brr[i] + dp1[i+1], crr[i] + dp0[i+1]); dp0[i] = Math.max(arr[i] + dp1[i+1], brr[i] + dp0[i+1]); }else{ dp0[i] = Math.max(arr[i] + dp1[i+1], brr[i] + dp0[i+1]); } } // for (int i = 1; i <= n; ++i){ // System.out.print(dp0[i] + " "); // } // System.out.println(); // for (int i = 1; i <= n; ++i){ // System.out.print(dp1[i] + " "); // } // System.out.println(); out = new PrintWriter(new BufferedOutputStream(System.out)); out.println(dp0[1]); out.close(); } public int calNum1(int z){ int res = 0; while (z > 0){ if (z % 2 != 0){ res++; } z /= 2; } return res; } public long Find(char[] arr, int n, int num){ int cur = 0; long res = 0L; for (int i = 0; i < n; ++i){ if (arr[i] == '1'){ if (i < (n-1)){ int rem = n - i - 1; if (rem >= num){ res = (res + C(rem, num)) % MOD; } // System.out.println(rem + " num: " + num + " curRes: " + res); } cur++; num--; if (num == 0){ res = (res + 1L) % MOD; break; } } } // System.out.println("total: " + res); return res; } long pow(int a, int b){ long x=1L; long y=(long)a; while(b > 0) { if(b%2 == 1) { x=(x*y); if(x>MOD) x%=MOD; } y = (y*y); if(y>MOD) y%=MOD; b /= 2L; } return x; } public long InverseEuler(int n){ return pow(n, (int)(MOD - 2L)); } public long C(int n, int k){ long p1 = InverseEuler((int)fac[k]); long p2 = InverseEuler((int)fac[n-k]); long p3 = (p1 * p2) % MOD; long res = (fac[n] * p3) % MOD; // System.out.println("---C n: " + n + " k: " + k + " res: " + res); return res; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
3fd8095b9d9048b5f3a05ba29f57c3de
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author caoash */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); DDimaAndHares solver = new DDimaAndHares(); solver.solve(1, in, out); out.close(); } static class DDimaAndHares { public void solve(int testNumber, FastScanner br, PrintWriter pw) { int N = br.nextInt(); int[] a = new int[N]; int[] b = new int[N]; int[] c = new int[N]; for (int i = 0; i < N; i++) { a[i] = br.nextInt(); } for (int i = 0; i < N; i++) { b[i] = br.nextInt(); } for (int i = 0; i < N; i++) { c[i] = br.nextInt(); } long[][] dp = new long[N][2]; for (int i = 0; i < N; i++) { for (int j = 0; j < 2; j++) { dp[i][j] = Integer.MIN_VALUE; } } dp[0][0] = a[0]; dp[0][1] = b[0]; for (int i = 1; i < N; i++) { dp[i][0] = Math.max(dp[i - 1][0] + b[i], dp[i - 1][1] + a[i]); dp[i][1] = Math.max(dp[i - 1][0] + c[i], dp[i - 1][1] + b[i]); } pw.println(dp[N - 1][0]); pw.close(); } } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastScanner.SpaceCharFilter filter; public FastScanner(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
4de5f1e2e6cbd67205efaafd6add2b52
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author ankur */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } static class TaskD { int[] a; int[] b; int[] c; int[][] dp; public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); a = in.nextIntArray(n); b = in.nextIntArray(n); c = in.nextIntArray(n); dp = in.initdp(n + 1, 3); long ans = solve(0, 0); out.println(ans); } int solve(int ind, int isbefore) { int ans = 0; if (ind == a.length - 1) { if (isbefore == 1) return b[ind]; return a[ind]; } if (dp[ind][isbefore] != -1) return dp[ind][isbefore]; if (isbefore == 1) { ans = Math.max(c[ind] + solve(+ind + 1, 0), b[ind] + solve(ind + 1, 1)); } else { ans = Math.max(a[ind] + solve(+ind + 1, 1), b[ind] + solve(ind + 1, 0)); } return dp[ind][isbefore] = ans; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar; private int snumChars; public InputReader(InputStream st) { this.stream = st; } public int read() { //*-*------clare------ //remeber while comparing 2 non primitive data type not used == 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 res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public int[][] initdp(int n, int m) { int ar[][] = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) ar[i][j] = -1; } return ar; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
292537f8979b2b1f55cdc2b3c0138d9e
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; import java.io.*; public class Main { public static Scanner in = new Scanner(System.in); static void swap(int []a,int i,int j) { int t = a[i]; a[i]=a[j]; a[j]=t; } static void select(int []a,int k) { int x = a[0]; for(int i=1;i<a.length;i++) { if(a[i]<=x) { swap(a,i,x); x=i; } } } static int solve(int n,int v,int k,boolean vis[][],int dp[][]) { //System.out.println(n+" "+v+" "+k); if(n<0) return 0; if(k==0 && n>0) return 0; if(n==0 && k==0) { vis[0][0]=true; return dp[n][k]=1; } if(vis[n][k]) return dp[n][k]; vis[n][k]=true; for(int i=v;i>=1;i--) dp[n][k]+=(solve(n-i,i,k-1,vis,dp))%1988; return dp[n][k]; } public static void main(String[] args) { int n = in.nextInt(); int a[]=new int[n],b[]=new int[n],c[]=new int[n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); for(int i=0;i<n;i++) b[i]=in.nextInt(); for(int i=0;i<n;i++) c[i]=in.nextInt(); if(n==1) { System.out.println(a[0]); return; } int dp[][]=new int[n][2]; dp[1][1]=b[1]+a[0]; dp[1][0]=a[1]+b[0]; for(int i=2;i<n;i++) { dp[i][0]=a[i]+(i>0?(Math.max(dp[i-1][1]+c[i-1]-b[i-1],dp[i-1][0]-a[i-1]+b[i-1])):0); dp[i][1]=b[i]+(i>0?(Math.max(dp[i-1][1],dp[i-1][0])):0); } System.out.println(Math.max(dp[n-1][0],dp[n-1][1])); //System.out.println(solve(7,7,3,new boolean[5001][5001],new int[5001][5001])); /*int n = in.nextInt(),m=in.nextInt(); int dp[][]=new int[n+1][n+1]; dp[0][0]=1; //for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { for(int k=0;k<=n;k++) { if(j-k>=0) dp[j][k]+=dp[j-k][k]; dp[j][k]+=dp[j-1][k]; dp[j][k]%=1988; } } //} //dp[m]=sum of all such dp[i] System.out.println(dp[n][m]); /*long a[]=new long[n]; long dp[][][]=new long[n][n][2]; long max[][][]=new long[n][n][2]; long sum[][]=new long[n][n]; for(int i=0;i<n;i++) a[i]=in.nextInt(); for(int i=0;i<n;i++) { sum[i][i]=a[i]; for(int j=i-1;j>=0;j--) { sum[i][j]=sum[i][j+1]+a[j]; } } dp[0][1][0]=a[0]; //dp[1][2][0]=a[0]+a[1]; for(int j=n-2;j>=0;j--) { max[0][j][0]=Math.max(max[0][j+1][0],dp[0][j][0]); max[0][j][1]=Math.max(max[0][j+1][1],dp[0][j][1]); max[1][j][0]=Math.max(max[1][j+1][0],dp[1][j][0]); max[1][j][1]=Math.max(max[1][j+1][1],dp[1][j][1]); } for(int i=1;i<n;i++) { for(int j=1;j<=i;j++) { if(i-j>=0) { dp[i][j][0]=Math.max(dp[i][j][0],max[i-j][(j+1)/2][1]+sum[i][i-j+1]); dp[i][j][1]=Math.max(dp[i][j][1],max[i-j][(j+1)/2][0]); } } max[i][n-1][0]=dp[i][n-1][0]; max[i][n-1][1]=dp[i][n-1][1]; for(int j=n-2;j>=0;j--) { max[i][j][0]=Math.max(max[i][j+1][0],dp[i][j][0]); max[i][j][1]=Math.max(max[i][j+1][1],dp[i][j][1]); } } long ans=0; for(int i=0;i<n;i++) { ans=Math.max(dp[n-1][i][0],ans); } System.out.println(ans);*/ } static public long read(long []t,int i) { long sum=0; while(i>0) { sum+=t[i]; i-=(i&-i); } return sum; } static public void upd(long []t,int i) { while(i<1000002) { t[i]++; i+=(i&-i); } } /* public static Scanner in = new Scanner(System.in); public static void main(String[] args) { int n = in.nextInt(),m=in.nextInt(); HashSet<String> h = new HashSet<String>(); for(int i=0;i<n;i++) { h.add(in.next()); } int cn=0; for(int j=0;j<m;j++) { if(h.contains(in.next())) cn++; } n-=cn; m-=cn; if(m-n<(cn%2)) System.out.println("YES"); else System.out.println("NO"); } /* public static void main(String[] args) { int n = in.nextInt(); Segments s[] = new Segments[n]; ArrayList<Long> xcord = new ArrayList<Long>(); for(int i=0;i<n;i++) { long x,y; s[i]=new Segments(x=in.nextLong(),y=in.nextLong()); in.nextInt(); xcord.add(2*x); xcord.add(2*y); } Collections.sort(xcord); ArrayList<Long> nxcord = new ArrayList<Long>(); for(int i=0;i<xcord.size()-1;i++) { nxcord.add((xcord.get(i)+xcord.get(i+1))/2); } xcord.addAll(nxcord); Collections.sort(xcord); for(int i=0;i<xcord.size();i++) { int j=i+1; long p = xcord.get(i); while(j<n && xcord.get(j)==xcord.get(i)) j++; int cn=0; for(int k=0;k<n;k++) { if(s[i].s<p && s[i].f>p) cn++; } for(int k=i-1;k>=0;k--) { } } }*/ } class Segments{ long s,f; Segments(long s,long f){ this.s = s; this.f = f; } } /* class dir{ boolean l,r,u,d; } class Node extends ArrayList<Node>{ private static final long serialVersionUID = 1L; double x,y; int i; boolean visited=false; Node(int x,int y,int i){ this.x = x; this.y = y; this.i=i; } void reset(){ visited = false; } boolean dfs(dir d,double mid,double w,double h,double [][]dists,double cmpr){ visited = true; if(x+mid>=w) d.r=true; if(x-mid<=0.0) d.l=true; if(y+mid>=h) d.u=true; if(y-mid<=0.0) d.d=true; if((d.l && d.d) || (d.u && d.r) || (d.l && d.r) || (d.u && d.d)) { return true; } for(Node n : this) { if(!n.visited) { boolean fl=false; if(dists[i][n.i]<=cmpr) fl|=n.dfs(d,mid,w,h,dists,cmpr); if(fl) return fl; } } return false; } double dist(Node n1,Node n2) { return sq(n1.x-n2.x)+sq(n1.y-n2.y); } double sq(double a) { return a*a; } } class ChristmasBinaryTree{ public int count(long d, int[] left, int[] right) { int n = left.length; int dp[][][]=new int[120][120][64]; for(int i=0;i<n;i++) { dp[i][left[i]][0]=1; dp[i][right[i]][0]=1; } while(d>0) { long k=0; for(;1<<k<=d;k++) { for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { for(int l=0;l<n;l++) { dp[i][l][(int)k+1]+= dp[i][j][(int)k]*dp[j][l][(int)k]; } } } } int ndp[][][]=new int[120][120][64]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { ndp[i][j][0]=dp[i][j][(int)k]; } } dp=ndp; d-=1<<(k-1); } int cn=0; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { cn+=dp[i][j][0]*dp[i][j][0]; } } return cn; } } /* public class Main { private static InputReader in = new InputReader(System.in); public static void main(String args[]) { StringBuilder s = new StringBuilder(); int t = in.readInt(); while(t>0) { t--; } System.out.println(s); } /*public static int solve(String s, int i,int j, int dp[][],boolean visited[][]) { if(i>j) return 0; if(i==j) return dp[i][j]=1; if(visited[i][j]) return dp[i][j]; visited[i][j]=true; solve(s,i+1,j,dp,visited); solve(s,i,j-1,dp,visited); if(s.charAt(i)==s.charAt(j)) { if(i+1==j) return dp[i][j]=2; else { return dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]+1; } }else { if(i+1==j) return dp[i][j]=1; return dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1]; } }*/ /* public static void main(String args[]) { int t = in.nextInt(); while(t>0) { int m = in.nextInt(), n = in.nextInt(); long p = in.nextLong(); long dp[][][]=new long[11][300][300]; for(int i=1;i<=m;i++) dp[1][i][i]=1; for(int i=1;i<n;i++) { for(int j=1;j<m;j++) { for(int k=1;k<=j;k++) { for(int l=k;l>=1;l--) { if(j+l<=m) dp[i+1][j+l][l]+=dp[i][j][k]; } } } } System.out.println(dp[n][m-1][2]); for(int i=n;i>0;i--) { for(int j=1;j<=m;j++) { if(dp[i][m-j][j]>=p) { //System.out.print(j+" "); m-=j; break; }else { p-=dp[i][m-j][j]; System.out.print(p+" "); } } } System.out.println(); t--; } }*/ class sh implements Comparable<sh>{ int h,w,i; sh(int a,int b,int c){ w=a; h=b; i=c; } @Override public int compareTo(sh o) { if(w==o.w) return h-o.h; return w-o.w; } } 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 byte read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public 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); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
917ef7d1c89ad0497787923fa629f705
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class D358 { static int[][] mem; static int[] none, half, full; public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); mem = new int[2][n]; none = new int[n]; half = new int[n]; full = new int[n]; for(int[] arr:mem) Arrays.fill(arr, -1); for(int i = 0;i<n;i++) none[i] = sc.nextInt(); for(int i = 0;i<n;i++) half[i] = sc.nextInt(); for(int i = 0;i<n;i++) full[i] = sc.nextInt(); System.out.println(dp(0,0)); } static int dp(int last, int idx){ if(idx==full.length-1) return last==0?none[idx]:half[idx]; if(mem[last][idx]!=-1) return mem[last][idx]; int ans = 0; if(last==0) ans = Math.max(none[idx]+dp(1,idx+1), half[idx]+dp(0,idx+1)); else ans = Math.max(half[idx]+dp(1,idx+1), full[idx]+dp(0,idx+1)); return mem[last][idx] = ans; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
e6ca027f3c18fcb225024995a56ed26e
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class DimaAndHares { //a both neighbours are hungry //b exactly one is full //c both neighbours are full static int n , a[] , b[] , c[]; static long[][] memo; //on this state( , x) if i go to next state( , x+1) with l = 1 -->this means that x will be fed before x+1 static long solve(int l , int idx){ if(idx == n) return 0; long ret = 0; if(memo[l][idx]!=-1) return memo[l][idx]; if(idx == n-1) ret= ((l==1)?b[idx]:a[idx]); else if(idx == 0) ret = Math.max(b[0]+solve(0,1), a[0]+solve(1,1)); else if(l == 1) ret = Math.max(b[idx] + solve(1,idx+1), c[idx] + solve(0 , idx+1)); else ret = Math.max(a[idx] + solve(1,idx+1), b[idx] + solve(0 , idx+1)); return memo[l][idx] = ret; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); n = sc.nextInt(); a = new int[n]; b = new int[n]; c = new int[n]; for(int i=0;i<n;i++) a[i] = sc.nextInt(); for(int i=0;i<n;i++) b[i] = sc.nextInt(); for(int i=0;i<n;i++) c[i] = sc.nextInt(); memo = new long[2][n+1]; for(int i=0;i<memo.length;i++) Arrays.fill(memo[i], -1); System.out.println(solve(0,0)); } static class Scanner{ StringTokenizer st;BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException {while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());return st.nextToken();} public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException {return Double.parseDouble(next());} public boolean ready() throws IOException {return br.ready();} } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
ba786ee0e31b734bea4d4439d8a44864
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class D { static int N; static int[] a, b, c; static int[][] memo; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); N = sc.nextInt(); a = new int[N]; b = new int[N]; c = new int[N]; for(int i = 0; i < N; i++) a[i] = sc.nextInt(); for(int i = 0; i < N; i++) b[i] = sc.nextInt(); for(int i = 0; i < N; i++) c[i] = sc.nextInt(); memo = new int[2][N]; Arrays.fill(memo[0], -1); Arrays.fill(memo[1], -1); out.println((dp(0, 0))); out.flush(); out.close(); } static int dp(int i, int last) { if(i == N) return 0; if(memo[last][i] != -1) return memo[last][i]; int leave = 0, take = 0; if(last == 0) { leave = dp(i + 1, 0); take = a[i] + dp(i + 1, 1); if(i < N - 1) take = Math.max(take, b[i] + dp(i + 1, 0)); } else { leave = dp(i + 1, 0); take = b[i] + dp(i + 1, 1); if(i > 0 && i < N - 1) take = Math.max(take, c[i] + dp(i + 1, 0)); } return memo[last][i] = Math.max(take, leave); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
dea6daa625431fc03c6ae8599554a878
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.List; import java.util.Random; import java.util.StringTokenizer; public class Main implements Runnable { int sz[]; int id[]; List<Integer> edges[]; long tree[]; private void solve() throws IOException { int n = nextInt(); int a[] = new int[n]; int b[] = new int[n]; int c[] = new int[n]; for (int i = 0; i < n; ++i) { a[i] = nextInt(); } for (int i = 0; i < n; ++i) { b[i] = nextInt(); } for (int i = 0; i < n; ++i) { c[i] = nextInt(); } int dp[][] = new int[n + 1][2]; // dp[i][j] stores the max total joy when 1..ith hares are fed with if (n == 1) { pw.println(a[0]); return; } dp[1][0] = a[0]; dp[1][1] = b[0]; for (int i = 1; i < n - 1; ++i) { int val = 0; for (int j = 0; j < 2; ++j) { // previously for (int k = 0; k < 2; ++k) { // current if (1 - j + k == 1) { val = b[i]; } else if (1 - j + k == 0) { val = a[i]; } else { // 1 - j + k == 2 val = c[i]; } dp[i + 1][k] = Math.max(dp[i + 1][k], dp[i][j] + val); } } } int ans = Math.max(dp[n - 1][0] + b[n - 1], dp[n - 1][1] + a[n - 1]); pw.println(ans); } void test() throws IOException { Random rnd = new Random(); for (int i = 0; i < 2; ++i) { int n = rnd.nextInt(30) + 1; int a[] = new int[n]; System.err.println(n); for (int j = 0; j < n; ++j) { a[j] = rnd.nextInt(2) + 1; System.err.print(a[j] + " "); } // solve(n, a); System.err.println(); } } BufferedReader br; StringTokenizer st; PrintWriter pw; public static void main(String args[]) { new Main().run(); } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in), 32768); pw = new PrintWriter(System.out); st = null; solve(); pw.flush(); pw.close(); br.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
889600f721f65fd01fedfba6dc285b50
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
//package codeforce; import java.io.*; import java.util.*; public class dimaandhares { static int[] a,b,c; static int[][] dp; static int n; public static void main(String[] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw=new PrintWriter(System.out); n=Integer.parseInt(br.readLine()); a=new int[n]; b=new int[n]; c=new int[n]; dp=new int[n][2]; StringTokenizer st1=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) { a[i]=Integer.parseInt(st1.nextToken()); } st1=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) { b[i]=Integer.parseInt(st1.nextToken()); } st1=new StringTokenizer(br.readLine()); for(int i=0;i<n;i++) { c[i]=Integer.parseInt(st1.nextToken()); } for(int k=0;k<n;k++) { dp[k][0]=-1; dp[k][1]=-1; } pw.println(function(0,0)); pw.close(); } //0 previous not taken,1 previous taken public static int function(int current,int prevs) { if(current>=n) { return 0; } if(dp[current][prevs]!=-1) { return dp[current][prevs]; } int ans=0; if(current==0) { ans=Math.max(function(current+1,0)+b[current],ans); ans=Math.max(function(current+1, 1)+a[current],ans); } if(current==(n-1)) { if(prevs==0) { ans=a[current]; } else { ans=b[current]; } } else { if(prevs==0) { ans=Math.max(function(current+1,0)+b[current],ans ); ans=Math.max(function(current+1,1)+a[current], ans); } else { ans=Math.max(function(current+1,0)+c[current], ans); ans=Math.max(function(current+1,1)+b[current], ans); } } return dp[current][prevs]=ans; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
4aa6250e9b4776f91a45944a1d6cad0c
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class P358D { static int[] a, b, c; static int[][] dp; public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); a = new int[n]; for (int i = 0; i < n; i++) a[i] = scan.nextInt(); b = new int[n]; for (int i = 0; i < n; i++) b[i] = scan.nextInt(); c = new int[n]; for (int i = 0; i < n; i++) c[i] = scan.nextInt(); dp = new int[n][2]; for (int[] A : dp) Arrays.fill(A, -1); System.out.println(max(0, 0)); } private static int max(int left, int fedL) { if (dp[left][fedL] >= 0) return dp[left][fedL]; if (left == a.length-1) { int ans = fedL == 0 ? a[left] : b[left]; return dp[left][fedL] = ans; } int ans = 0; //Feed left hare first int joy = fedL == 0 ? a[left] : b[left]; ans = Math.max(ans, joy + max(left+1, 1)); //Feed left hare last joy = fedL == 0 ? b[left] : c[left]; ans = Math.max(ans, joy + max(left+1, 0)); return dp[left][fedL] = ans; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
eab1783cb0d0686d915130d6dece2552
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main { int n; long[][] dp = new long[3002][3]; int[][] val = new int[3002][3]; public void solve() throws IOException{ n = in.nextInt(); for(int i = 0; i < n; i++){ val[i][0] = in.nextInt(); } for(int i = 0; i < n; i++){ val[i][1] = in.nextInt(); } for(int i = 0; i < n; i++){ val[i][2] = in.nextInt(); } val[0][2] = 0; val[n - 1][2] = 0; for(int i = 0; i < 3002; i++){ Arrays.fill(dp[i], -1); } search(0, 0); out.println(dp[0][0]); return; } public long search(int cur, int prev){ if(dp[cur][prev] != -1){ return dp[cur][prev]; }else if(cur == n){ return 0; } long max = 0; if(prev == 1){ // prev is fed max = Math.max(max, search(cur + 1, 0) + val[cur][2]); // at last max = Math.max(max, search(cur + 1, 1) + val[cur][1]); // at current }else if(prev == 0){ max = Math.max(max, search(cur + 1, 1) + val[cur][0]); if(cur != n - 1){ max = Math.max(max, search(cur + 1, 0) + val[cur][1]); // } } dp[cur][prev] = max; return max; } public BigInteger gcdBigInt(BigInteger a, BigInteger b){ if(a.compareTo(BigInteger.valueOf(0L)) == 0){ return b; }else{ return gcdBigInt(b.mod(a), a); } } FastScanner in; PrintWriter out; static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { if (st == null || !st.hasMoreTokens()) return br.readLine(); StringBuilder result = new StringBuilder(st.nextToken()); while (st.hasMoreTokens()) { result.append(" "); result.append(st.nextToken()); } return result.toString(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, false); solve(); out.close(); } public static void main(String[] args) throws IOException{ new Main().run(); } public void printArr(int[] arr){ for(int i = 0; i < arr.length; i++){ out.print(arr[i] + " "); } out.println(); } public long gcd(long a, long b){ if(a == 0) return b; return gcd(b % a, a); } public boolean isPrime(long num){ if(num == 0 || num == 1){ return false; } for(int i = 2; i * i <= num; i++){ if(num % i == 0){ return false; } } return true; } public class Pair<A, B>{ public A x; public B y; Pair(A x, B y){ this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (!x.equals(pair.x)) return false; return y.equals(pair.y); } @Override public int hashCode() { int result = x.hashCode(); result = 31 * result + y.hashCode(); return result; } } class Tuple{ int x; int y; int z; Tuple(int ix, int iy, int iz){ x = ix; y = iy; z = iz; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
051eb62ff2c226ce0afb9235fff08ac2
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Writer; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.NoSuchElementException; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Stanislav Pak */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskD solver = new TaskD(); solver.solve(1, in, out); out.close(); } } class TaskD { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; for (int i = 0; i < n; ++i) { a[i] = in.readInt(); } for (int i = 0; i < n; ++i) { b[i] = in.readInt(); } for (int i = 0; i < n; ++i) { c[i] = in.readInt(); } long[][] d = new long[2][n]; ArrayUtils.fill(d, 0); d[0][0] = a[0]; d[1][0] = b[0]; for (int i = 1; i < n; ++i) { d[0][i] = Math.max(d[0][i], d[0][i - 1] + b[i]); d[0][i] = Math.max(d[0][i], d[1][i - 1] + a[i]); d[1][i] = Math.max(d[1][i], d[0][i - 1] + c[i]); d[1][i] = Math.max(d[1][i], d[1][i - 1] + b[i]); } out.printLine(d[0][n - 1]); } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void close() { writer.close(); } public void printLine(long i) { writer.println(i); } } class ArrayUtils { public static void fill(long[][] array, long value) { for (long[] row : array) Arrays.fill(row, value); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
48e406c1f11728edabac7cec147d7c8e
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; 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.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Scanner; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeSet; import java.lang.Long; public class Test { static long mod = 1000000007; static int[][] dp; static int contains; public static void main(String[] args) throws FileNotFoundException { PrintWriter out = new PrintWriter(System.out); Scanner in = new Scanner(); int n = in.nextInt(); int[][] data = new int[3][n]; for (int i = 0; i < 3; i++) { for (int j = 0; j < n; j++) { data[i][j] = in.nextInt(); } } dp = new int[2][n]; for (int[] a : dp) { Arrays.fill(a, -1); } int result = cal(0, 0, n, data); out.println(result); out.close(); } static int cal(int index, int pre, int n, int[][] data) { if (index == n) { return 0; } if (dp[pre][index] != -1) { return dp[pre][index]; } int result = 0; if (pre == 1) { int tmp = data[1][index] + cal(index + 1, 1, n, data); int tmp1 = 0; if (index + 1 < n) { tmp1 = data[2][index] + cal(index + 1, 0, n, data); } result = Math.max(tmp, tmp1); } else { int tmp = data[0][index] + cal(index + 1, 1, n, data); int tmp1 = 0; if (index + 1 < n) { tmp1 = data[1][index] + cal(index + 1, 0, n, data); } result = Math.max(tmp, tmp1); } return dp[pre][index] = result; } static int crossProduct(Point a, Point b) { return a.x * b.y + a.y * b.x; } static long squareDist(Point a) { long x = a.x; long y = a.y; return x * x + y * y; } static Point minus(Point a, Point b) { return new Point(a.x - b.x, a.y - b.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 Point { int x, y; public Point(int x, int y) { super(); this.x = x; this.y = y; } public String toString() { return "{" + x + " " + y + "}"; } } static class Entry implements Comparable<Entry> { int x, cost; public Entry(int x, int cost) { super(); this.x = x; this.cost = cost; } public int compareTo(Entry o) { // TODO Auto-generated method stub if (cost > o.cost) { return 1; } else if (cost == o.cost) { return -1; } return 0; } } static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } 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("B-large.in")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output