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
sequencelengths 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 | 29b33ee5826538a8270215fe1ca95b4b | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.util.Scanner;
public class divide {
public static void main(String[] args) {
Scanner ip=new Scanner(System.in);
int t=ip.nextInt();
long a[]=new long[t];
for(int i=0;i<t;i++)
{
a[i]=ip.nextLong();
}
for(int i=0;i<t;i++)
{ int count=0;
long num=a[i];
Boolean c=true;
while (num != 1){
if(num % 5 == 0)
num = (num / 5) * 4;
else if(num % 3 == 0)
num = (num / 3) * 2;
else if(num % 2 == 0)
num /= 2;
else{
System.out.println("-1");
c = false;
break;
}
count++;
}
if(c)
System.out.println(count);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 3168a3d22afa8b2848ec628edffadf2e | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class divideit{
static int steps(long k){
if(k%5!=0 && k%3!=0 && ((k&(k-1))!=0) &&k>1)
return Integer.MIN_VALUE;
if(k==1)
return 0;
if(k%5==0)
return 1+steps(4*(k/5));
else if(k%3==0)
return 1+steps(2*(k/3));
else if((k&(k-1))==0){
return (int)(Math.log(k)/Math.log(2));
}
return Integer.MIN_VALUE;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int tc=sc.nextInt();
while(tc-->0){
long k=sc.nextLong();
int res=steps(k);
if(res<0)
System.out.println("-1");
else
System.out.println(res);
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | fa70950329d5e47232487d417e8de0f8 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class DivideIt {
private static int solve(long n) {
int moves = 0;
while (n > 1) {
if ((n % 2) == 0) {
n /= 2;
} else if ((n % 3) == 0) {
n = n / 3 * 2;
} else if ((n % 5) == 0) {
n = n / 5 * 4;
} else {
return -1;
}
++moves;
}
return moves;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int q = s.nextInt();
while (q-- > 0) {
long n = s.nextLong();
System.out.println(solve(n));
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | df068810d0479ff1d9e3c543e337a074 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | // https://codeforces.com/problemset/problem/1176/A
import java.util.*;
public class DivideIt {
private static int solve(long n) {
int moves = 0;
while (n > 1) {
if ((n % 2) == 0) {
n /= 2;
} else if ((n % 3) == 0) {
n = n / 3 * 2;
} else if ((n % 5) == 0) {
n = n / 5 * 4;
} else {
return -1;
}
++moves;
}
return moves;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int q = s.nextInt();
while (q-- > 0) {
long n = s.nextLong();
System.out.println(solve(n));
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 038ab592615f1069e2f45726f7685462 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import static java.lang.Math.*;
public class Demo{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int q = in.nextInt();
while(q-->0){
int r=0;
long n = in.nextLong();
int a=0,b=0,c=0;
while (n!=1){
if (n%2==0){
n/=2;
a++;
} else if(n%3==0){
n/=3;
b++;
} else if(n%5==0){
n/=5;
c++;
} else{
r = -1;
break;
}
}
System.out.println(r==-1 ? r:a+2*b+3*c);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 1f8545041b6d2e362d0776c0963ed63a | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Greedy_A_DivideIt {
public static void main(String[] args) throws Exception
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
Long n=sc.nextLong();
solve(n);
}
sc.close();
}
public static void solve(Long n) {
int count=0;
while(n!=1)
{
if(n%2==0)
{
n=n/2;
count++;
}
else if(n%3==0)
{
n=2*(n/3);
count++;
}
else if(n%5==0)
{
n=4*(n/5);
count++;
}
else
{
System.out.println(-1);
return ;
}
}
System.out.println(count);
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 78ddc66339d680cebbfafcf1cc5706ef | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class _0166Divideit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cases=sc.nextInt();
while(cases>0) {
long n=sc.nextLong();
int moves=0;
while(n>1) {
if(n%5==0) {
n=4*n/5;
}
else if(n%3==0) {
n=2*n/3;
}
else if(n%2==0) {
n=n/2;
}
else {
moves=-1;
break;
}
moves++;
}
System.out.println(moves);
cases--;
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | ff1c2d598e8bd391e73d0e263e852983 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | /*==============================================
Name : Shadman Shariar ||
Email : [email protected] ||
University : North South University (NSU) ||
Facebook : shadman.shahriar.007 ||
==============================================*/
import java.util.Scanner;
public class Main {
public static int binarysearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarysearch(arr, l, mid - 1, x);
return binarysearch(arr, mid + 1, r, x);
}
return -1;
}
public static int sumofarray(int arr[])
{
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum += arr[i];
return sum;
}
public static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
public static void rangeofprimenumber(int a, int b)
{
int i, j, flag;
for (i = a; i <= b; i++) {
if (i == 1 || i == 0)
continue;
flag = 1;
for (j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1)
System.out.println(i);
}
}
public static boolean isprime(int n)
{
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i += 2)
{
if (n % i == 0)
return false;
}
return true;
}
public static int factorial(int n)
{
return (n == 1 || n == 0) ? 1 : n * factorial(n - 1);
}
public static int[] reveresearray(int arr[],
int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
return arr;
}
public static int totaldivisor(int n)
{
int c = 0;
for (int i=1;i<=n;i++)
if (n%i==0)c++;
return c;
}
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int t = input.nextInt();
for (int i = 0; i < t; i++) {
long n = input.nextLong();
int c = 0 ;
while (n!=1) {
if (n%2==0) {
n = n/2;
c++;
}
else if (n%3==0) {
n = (n*2)/3;
c++;
}
else if (n%5==0) {
n = (n*4)/5;
c++;
}
else {
break;
}
}
if (n!=1) {
System.out.println(-1);
}
else {
System.out.println(c);
}
}
input.close();
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | ff9dadf20220e482ad85c579ea59f0f7 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class java {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int tt = s.nextInt();
while(tt-- > 0) {
long n = s.nextLong();
int a = 0, b = 0, c = 0;
while(n%2 == 0) {
n /= 2;
a++;
}
while(n%3 == 0) {
n /= 3;
b++;
}
while(n%5 == 0) {
n /= 5;
c++;
}
int ans;
if(n == 1) {
ans = a + 2*b + 3*c;
} else {
ans = -1;
}
System.out.println(ans);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | f748172ead9396dc1645459981645427 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
//import java.util.Scanner;
/**
*
* @author DELL
*/
public class Main{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int track=1;
int t=sc.nextInt();
while(t-->0){
long n = sc.nextLong();
int count=0;
while(true){
boolean b=false;
if(n%2==0){
n=n/2;
b=true;
}
else if(n%3==0){
n=(2*n)/3;
b=true;
}
else if(n%5==0){
n=(n*4)/5;
b=true;
}
if(!b)break;
count++;
}
if(n==1)System.out.println(count);
else System.out.println("-1");
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | b58b6eee2655081886d5973b8c011eac | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class A1176 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int q = input.nextInt();
for (int i = 0; i < q; i++) {
int counter = 0;
long n = input.nextLong();
while(n%5 == 0){
counter++;
n = 4*n/5;
}
while(n%3 == 0){
counter++;
n = 2*n/3;
}
while(n%2 == 0){
counter++;
n = n/2;
}
if(n == 1){
System.out.println(counter);
}else{
System.out.println(-1);
}
}
input.close();
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 02bf3e02d13a3178086d762108d0ba27 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Solve1 {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)),true);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.flush();
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter pw) {
int n=in.nextInt();
for(int i=0;i<n;i++) {
long q=in.nextLong();
long temp=q;
int count=0;
while(temp>1) {
if(temp==1) {
break;
}else if(temp%2==0) {
temp/=2;
count++;
}else if(temp%3==0) {
temp=((temp*2)/3);
count++;
}else if(temp%5==0){
temp=temp*4/5;
count++;
}else {
count=-1;
break;
}
}
pw.println(count);
}
}
}
class InputReader{
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in){
br=new BufferedReader(new InputStreamReader(in));
st=null;
}
public String next(){
while(st==null||!st.hasMoreTokens()){
try{
st=new StringTokenizer(br.readLine());
}catch(IOException e){
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | be1827b560ca9968104cbe00f2d2accd | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class DivideIt{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
long n = sc.nextLong();
long count=0;
int flag=0;
while(n>1)
{
if(n%2==0)
{
count++;
n=n/2;
}
else if(n%3==0)
{
count++;
n=2*n/3;
}
else if(n%5==0)
{
count++;
n=4*n/5;
}
else
{
System.out.println("-1");
flag=1;
break;
}
}
if(flag==0)
System.out.println(count);
t--;
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 06f8411ff43145825c2c0dd6a035778d | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int q = input.nextInt();
while(q-->0) {
long n = input.nextLong();
int count = 0;
if(n==1) {
System.out.println(0);
}
else {
while(n>1) {
if(n%2==0) {
n/=2;
count++;
}
else if(n%3==0) {
n = (2*n)/3;
count++;
}
else if(n%5==0) {
n = (4*n)/5;
count++;
}
else {
System.out.println(-1);
count = 0;
break;
}
}
if(count > 0) {
System.out.println(count);
}
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | d78bf986c5153cb8abc2f4fd4e020646 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int o=sc.nextInt();
while(o-->0) {
long a=sc.nextLong();
int sum = 0;
while(a%5==0) {
a=a/5*4;
sum++;
}
while(a%3==0) {
a=a/3*2;
sum++;
}
while(a%2==0) {
a/=2;
sum++;
}
if(a!=1)
System.out.println(-1);
else
System.out.println(sum);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 137a71c834e9f2f2e77673d7f86d0c70 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner input = new Scanner(System.in);
int test = input.nextInt();
while(test-->0){
long n = input.nextLong();
int count =0;
boolean ok = false;
while(true){
if(n == 1)break;
if(n%2 == 0)n/=2;
else if(n%3 == 0)n=(2*n)/3;
else if(n%5 == 0)n=(4*n)/5;
else {
ok = true;
break;
}
count++;
}
if(!ok)System.out.println(count);
else System.out.println(-1);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | a1a7f1433ffbde8270319dbe105222c2 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) {
FastReader sc=new FastReader();
int t=sc.nextInt();
StringBuilder sb=new StringBuilder();
while(t-->0) {
long n=sc.nextLong();
long k=n;
int c1=0,c2=0,c3=0;
while(k%5==0) {
c1++;
k=4*k/5;
}
while(k%3==0) {
c2++;
k=2*k/3;
}
while(k%2==0) {
c3++;
k=k/2;
}
if(k!=1) {
System.out.println(-1);
}
else {
System.out.println(c1+c2+c3);
}
}
}
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 | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | ac43943980ff456f39aa5359c1ed0a8e | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class cf_1176_a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tt = sc.nextInt();
while (tt-- > 0) {
long ans = 0;
long n = sc.nextLong();
while (true) {
if (n % 2 == 0) {
ans += 1;
n /= 2;
} else if (n % 3 == 0) {
ans += 2;
n /= 3;
} else if (n % 5 == 0) {
ans += 3;
n /= 5;
} else {
break;
}
}
if (n > 1) ans = -1;
System.out.println(ans);
}
sc.close();
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 5656a6047ebf10e3acade06c45bc63fc | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.Arrays;
import java.math.BigInteger;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in =new Scanner(System.in);
int t=1,i,j,m=0,k,p=0,h,l,x,y,d;
String s="",st;
long n;
t=in.nextInt();
for(i=0;i<t;i++)
{
p=0;
n=in.nextLong();
while(n%2==0)
{
n=n/2;
p++;
}
while(n%3==0)
{
n=(n/3)*2;
p+=2;
}
while(n%5==0)
{
n=(n/5)*4;
p+=3;
}
while(n%2==0)
n=n/2;
if(n==1)
System.out.println(p);
else
System.out.println("-1");
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | ca14aa807dbd338ca9242714b795d595 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class d {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int q,count=0;
q=input.nextInt();
for(int i=0;i<q;i++){
long n,a;
n=input.nextLong();
a=n;
while(a!=1){
if(a%2==0){
a=a/2;
count++;
}
else if(a%3==0)
{
a=(2*a)/3;
count++;
}
else if(a%5==0)
{ a=(4*a)/5;
count++;
}
else{
System.out.println("-1");
break;
}
}
if(n==1)
{ System.out.println("0"); }
else if(count!=0 && a==1){
System.out.println(count); }
count=0; } }
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 6760dba8ed3046e371f03f41e87b1808 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner s= new Scanner(System.in);
int t = s.nextInt();
while(t-->0){
long n = s.nextLong();
int count = 0;
while(n>1){
if(n%5 == 0)
n = 4*n/5;
else if(n%3 == 0)
n = 2*n/3;
else if(n%2 == 0)
n/=2;
else
{
count = -1;
break;
}
count++;
}
System.out.println(count);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 6bd5d4ec887f2fa5cb3f418f660092e8 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A1176_DivideIt {
public static void main(String[] args) {
PrintWriter pw = new PrintWriter(System.out);
int q = nextInt();
while (q-- != 0) {
long n = nextLong();
int cnt = 0;
while (n != 1) {
if (n % 2 == 0) {
n /= 2;
cnt++;
} else if (n % 3 == 0) {
n = 2 * n / 3;
cnt++;
} else if (n % 5 == 0) {
n = 4 * n / 5;
cnt++;
} else break;
}
pw.println(n == 1 ? cnt : -1);
}
pw.close();
}
private static final long MOD = (long) (Math.pow(10, 9) + 7);
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer st;
private static String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
private static String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
private static int nextInt() {
return Integer.parseInt(next());
}
private static long nextLong() {
return Long.parseLong(next());
}
private static double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 16902952e324ae3ca7ba73f5f5452fe7 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
public class Solution{
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
int test = sc.nextInt();
while(test -->0){
long n = sc.nextLong();
int c1 = 0,c2 = 0, c3 =0;
while(n % 2 == 0){
n = n / 2;
c1++;
}
while(n % 3 == 0){
n = n / 3;
c2++;
}
while(n % 5 == 0){
n = n / 5;
c3++;
}
if(n != 1)
System.out.println(-1);
else
System.out.println(c1+2*c2+c3*3);
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 6a590057ce02465df73951042dd7750e | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class codeforces
{
public static void main (String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while(n-->0){
long x = sc.nextLong();
int num = 0;
while(x%5==0){
x=x/5*4;
num++;
}
while(x%3==0){
x=x/3*2;
num++;
}
while(x%2==0){
x/=2;
num++;
}
if(x!=1){
System.out.println(-1);
}else{
System.out.println(num);
}
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 7afddddff8c261d335898f3a60b35579 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
// Compiler version JDK 11.0.2
public class Dcoder
{
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 (Exception e){
e.printStackTrace();
}
return str;
}
}
public static void main(String args[])
{
FastReader in = new FastReader();
int t = in.nextInt();
while(t-->0){
long n = in.nextLong();
Set<Long> s = new HashSet<>();
int ans = 0;
boolean ok = true;
while(n!=1){
ok=false;
long n1 = n, n2 = n, n3 = n;
if(n%2==0){
n1=Math.min(n1,n1/2);
ok=true;
}
if(n%3==0){
n2=Math.min(n2,2*n2/3);
ok=true;
}
if(n%5==0){
n3=Math.min(n3,4*n3/5);
ok=true;
}
ans++;
n = Math.min(n1,Math.min(n2,n3));
if(!ok || s.contains(n)){
ok = false; break;
}
s.add(n);
}
System.out.println(ok?ans:"-1");
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 6f3340c92bdcd83143c69fd8648775c4 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | //package com.company;
import java.io.*;
import java.util.*;
public class Divideit {
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
MyScanner sc = new MyScanner();//start
int n=sc.nextInt();
while (0<n--){
long x =sc.nextLong();
int two=0,three=0,five=0;
while(x%2==0){x/=2;two++;}
while(x%3==0){x/=3;three++;}
while(x%5==0){x/=5;five++;}
if(x==1){
out.println(two+three*2+five*3);//why 3 good question //no idea
}else {
out.println(-1);
}
}
out.println();
out.close();
}
//-----------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 | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 99df3f12bd706b36ceaa33f82ca1245f | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
import java.lang.Math;
public class Hello{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i = 0; i<t; i++){
long n = sc.nextLong(), five = 0, three = 0, two = 0;
while(n%5==0){
n = n/5;
five++;
}
while(n%3==0){
n = n/3;
three++;
}
while(n%2==0){
n = n/2;
two++;
}
if(n!=1)
System.out.println(-1);
else
System.out.println(3*five + 2*three + two);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 8b6b6bcc32507c5e2c027c382b728188 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class DivideIt {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
while (q > 0) {
long n = sc.nextLong();
int count = 0;
while (n > 1) {
if (n % 2 == 0) {
n /= 2;
} else if (n % 3 == 0) {
n = (n * 2) / 3;
} else if (n % 5 == 0) {
n = (n * 4) / 5;
}else {
count =-1;
break;
}
count++;
}
System.out.println(count);
q--;
}
sc.close();
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 22810b2fd9ca63a0c9236053640c3000 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | /*
Author: Anthony Ngene
Created: 18/09/2020 - 05:38
*/
import java.io.*;
import java.util.*;
public class A {
// The only thing we have to fear is fear itself. - Franklin CodeForces.Div3.CF1385_656.P1.D. Roosevelt
void solver() throws IOException {
int cases = in.intNext();
for (int t = 1; t <= cases; t++) {
long n = in.longNext();
int count = 0;
while (n > 1) {
if (n % 2 == 0) {
n /= 2;
} else if (n % 3 == 0) {
n = (n * 2) / 3;
} else if (n % 5 == 0) {
n = (n * 4) / 5;
} else {
break;
}
count++;
}
out.println(n <= 1 ? count : -1);
}
}
// Generated Code Below:
// checks: 1. edge cases 2. overflow 3. possible errors (e.g 1/0, arr[out]) 4. time/space complexity
private static final FastWriter out = new FastWriter();
private static FastScanner in;
static ArrayList<Integer>[] adj;
private static long e97 = (long)1e9 + 7;
public static void main(String[] args) throws IOException {
in = new FastScanner();
new A().solver();
out.close();
}
static class FastWriter {
private static final int IO_BUFFERS = 128 * 1024;
private final StringBuilder out;
public FastWriter() { out = new StringBuilder(IO_BUFFERS); }
public FastWriter p(Object object) { out.append(object); return this; }
public FastWriter p(String format, Object... args) { out.append(String.format(format, args)); return this; }
public FastWriter pp(Object... args) { for (Object ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(int[] args) { for (int ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(long[] args) { for (long ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public FastWriter pp(char[] args) { for (char ob : args) { out.append(ob).append(" "); } out.append("\n"); return this; }
public void println(long[] arr) { for(long e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(int[] arr) { for(int e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(char[] arr) { for(char e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(double[] arr) { for(double e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(boolean[] arr) { for(boolean e: arr) out.append(e).append(" "); out.append("\n"); }
public <T>void println(T[] arr) { for(T e: arr) out.append(e).append(" "); out.append("\n"); }
public void println(long[][] arr) { for (long[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(int[][] arr) { for (int[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(char[][] arr) { for (char[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public void println(double[][] arr) { for (double[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public <T>void println(T[][] arr) { for (T[] row: arr) out.append(Arrays.toString(row)).append("\n"); }
public FastWriter println(Object object) { out.append(object).append("\n"); return this; }
public void toFile(String fileName) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(out.toString());
writer.close();
}
public void close() throws IOException { System.out.print(out); }
}
static class FastScanner {
private InputStream sin = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
public FastScanner(){}
public FastScanner(String filename) throws FileNotFoundException {
File file = new File(filename);
sin = new FileInputStream(file);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = sin.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
public boolean hasNext() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++; return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long longNext() {
if (!hasNext()) throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while(true){
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
}else if(b == -1 || !isPrintableChar(b) || b == ':'){
return minus ? -n : n;
}else{
throw new NumberFormatException();
}
b = readByte();
}
}
public int intNext() {
long nl = longNext();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
return (int) nl;
}
public double doubleNext() { return Double.parseDouble(next());}
public long[] nextLongArray(final int n){
final long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = longNext();
return a;
}
public int[] nextIntArray(final int n){
final int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = intNext();
return a;
}
public double[] nextDoubleArray(final int n){
final double[] a = new double[n];
for (int i = 0; i < n; i++)
a[i] = doubleNext();
return a;
}
public ArrayList<Integer>[] getAdj(int n) {
ArrayList<Integer>[] adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) adj[i] = new ArrayList<>();
return adj;
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges) throws IOException {
return adjacencyList(nodes, edges, false);
}
public ArrayList<Integer>[] adjacencyList(int nodes, int edges, boolean isDirected) throws IOException {
adj = getAdj(nodes);
for (int i = 0; i < edges; i++) {
int a = intNext(), b = intNext();
adj[a].add(b);
if (!isDirected) adj[b].add(a);
}
return adj;
}
}
static class u {
public static int upperBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int upperBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj < array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(long[] array, long obj) {
int l = 0, r = array.length - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array[c]) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
public static int lowerBound(ArrayList<Long> array, long obj) {
int l = 0, r = array.size() - 1;
while (r - l >= 0) {
int c = (l + r) / 2;
if (obj <= array.get(c)) {
r = c - 1;
} else {
l = c + 1;
}
}
return l;
}
static <T> T[][] deepCopy(T[][] matrix) { return Arrays.stream(matrix).map(el -> el.clone()).toArray($ -> matrix.clone()); }
static int[][] deepCopy(int[][] matrix) { return Arrays.stream(matrix).map(int[]::clone).toArray($ -> matrix.clone()); }
static long[][] deepCopy(long[][] matrix) { return Arrays.stream(matrix).map(long[]::clone).toArray($ -> matrix.clone()); }
private static void sort(int[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static void sort(long[][] arr){ Arrays.sort(arr, Comparator.comparingDouble(o -> o[0])); }
private static <T>void rSort(T[] arr) { Arrays.sort(arr, Collections.reverseOrder()); }
private static void customSort(int[][] arr) {
Arrays.sort(arr, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] == b[0]) return Integer.compare(a[1], b[1]);
return Integer.compare(a[0], b[0]);
}
});
}
public static int[] swap(int[] arr, int left, int right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static char[] swap(char[] arr, int left, int right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
return arr;
}
public static int[] reverse(int[] arr, int left, int right) {
while (left < right) {
int temp = arr[left];
arr[left++] = arr[right];
arr[right--] = temp;
}
return arr;
}
public static boolean findNextPermutation(int[] data) {
if (data.length <= 1) return false;
int last = data.length - 2;
while (last >= 0) {
if (data[last] < data[last + 1]) break;
last--;
}
if (last < 0) return false;
int nextGreater = data.length - 1;
for (int i = data.length - 1; i > last; i--) {
if (data[i] > data[last]) {
nextGreater = i;
break;
}
}
data = swap(data, nextGreater, last);
data = reverse(data, last + 1, data.length - 1);
return true;
}
public static int biSearch(int[] dt, int target){
int left=0, right=dt.length-1;
int mid=-1;
while(left<=right){
mid = (right+left)/2;
if(dt[mid] == target) return mid;
if(dt[mid] < target) left=mid+1;
else right=mid-1;
}
return -1;
}
public static int biSearchMax(long[] dt, long target){
int left=-1, right=dt.length;
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt[mid] <= target) left=mid;
else right=mid;
}
return left;
}
public static int biSearchMaxAL(ArrayList<Integer> dt, long target){
int left=-1, right=dt.size();
int mid=-1;
while((right-left)>1){
mid = left + (right-left)/2;
if(dt.get(mid) <= target) left=mid;
else right=mid;
}
return left;
}
private static <T>void fill(T[][] ob, T res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(boolean[][] ob,boolean res){for(int i=0;i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][] ob, int res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(long[][] ob, long res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(char[][] ob, char res){ for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(double[][] ob, double res){for(int i=0; i<ob.length; i++){ for(int j=0; j<ob[0].length; j++){ ob[i][j] = res; }}}
private static void fill(int[][][] ob,int res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill(long[][][] ob,long res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static <T>void fill(T[][][] ob,T res){for(int i=0;i<ob.length;i++){for(int j=0;j<ob[0].length;j++){for(int k=0;k<ob[0][0].length;k++){ob[i][j][k]=res;}}}}
private static void fill_parent(int[] ob){ for(int i=0; i<ob.length; i++) ob[i]=i; }
private static boolean same3(long a, long b, long c){
if(a!=b) return false;
if(b!=c) return false;
if(c!=a) return false;
return true;
}
private static boolean dif3(long a, long b, long c){
if(a==b) return false;
if(b==c) return false;
if(c==a) return false;
return true;
}
private static double hypotenuse(double a, double b){
return Math.sqrt(a*a+b*b);
}
private static long factorial(int n) {
long ans=1;
for(long i=n; i>0; i--){ ans*=i; }
return ans;
}
private static long facMod(int n, long mod) {
long ans=1;
for(long i=n; i>0; i--) ans = (ans * i) % mod;
return ans;
}
private static long lcm(long m, long n){
long ans = m/gcd(m,n);
ans *= n;
return ans;
}
private static long gcd(long m, long n) {
if(m < n) return gcd(n, m);
if(n == 0) return m;
return gcd(n, m % n);
}
private static boolean isPrime(long a){
if(a==1) return false;
for(int i=2; i<=Math.sqrt(a); i++){ if(a%i == 0) return false; }
return true;
}
static long modInverse(long a, long mod) {
/* Fermat's little theorem: a^(MOD-1) => 1
Therefore (divide both sides by a): a^(MOD-2) => a^(-1) */
return binpowMod(a, mod - 2, mod);
}
static long binpowMod(long a, long b, long mod) {
long res = 1;
while (b > 0) {
if (b % 2 == 1) res = (res * a) % mod;
a = (a * a) % mod;
b /= 2;
}
return res;
}
private static int getDigit2(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf = 1<<d; }
return d;
}
private static int getDigit10(long num){
long cf = 1; int d=0;
while(num >= cf){ d++; cf*=10; }
return d;
}
private static boolean isInArea(int y, int x, int h, int w){
if(y<0) return false;
if(x<0) return false;
if(y>=h) return false;
if(x>=w) return false;
return true;
}
private static ArrayList<Integer> generatePrimes(int n) {
int[] lp = new int[n + 1];
ArrayList<Integer> pr = new ArrayList<>();
for (int i = 2; i <= n; ++i) {
if (lp[i] == 0) {
lp[i] = i;
pr.add(i);
}
for (int j = 0; j < pr.size() && pr.get(j) <= lp[i] && i * pr.get(j) <= n; ++j) {
lp[i * pr.get(j)] = pr.get(j);
}
}
return pr;
}
static long nPrMod(int n, int r, long MOD) {
long res = 1;
for (int i = (n - r + 1); i <= n; i++) {
res = (res * i) % MOD;
}
return res;
}
static long nCr(int n, int r) {
if (r > (n - r))
r = n - r;
long ans = 1;
for (int i = 1; i <= r; i++) {
ans *= n;
ans /= i;
n--;
}
return ans;
}
static long nCrMod(int n, int r, long MOD) {
long rFactorial = nPrMod(r, r, MOD);
long first = nPrMod(n, r, MOD);
long second = binpowMod(rFactorial, MOD-2, MOD);
return (first * second) % MOD;
}
static void printBitRepr(int n) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < 32; i++) {
int mask = (1 << i);
res.append((mask & n) == 0 ? "0" : "1");
}
out.println(res);
}
static String bitString(int n) {return Integer.toString(n);}
static int setKthBitToOne(int n, int k) { return (n | (1 << k)); } // zero indexed
static int setKthBitToZero(int n, int k) { return (n & ~(1 << k)); }
static int invertKthBit(int n, int k) { return (n ^ (1 << k)); }
static boolean isPowerOfTwo(int n) { return (n & (n - 1)) == 0; }
static HashMap<Character, Integer> counts(String word) {
HashMap<Character, Integer> counts = new HashMap<>();
for (int i = 0; i < word.length(); i++) counts.merge(word.charAt(i), 1, Integer::sum);
return counts;
}
static HashMap<Integer, Integer> counts(int[] arr) {
HashMap<Integer, Integer> counts = new HashMap<>();
for (int value : arr) counts.merge(value, 1, Integer::sum);
return counts;
}
static HashMap<Long, Integer> counts(long[] arr) {
HashMap<Long, Integer> counts = new HashMap<>();
for (long l : arr) counts.merge(l, 1, Integer::sum);
return counts;
}
static HashMap<Character, Integer> counts(char[] arr) {
HashMap<Character, Integer> counts = new HashMap<>();
for (char c : arr) counts.merge(c, 1, Integer::sum);
return counts;
}
static long hash(int x, int y) {
return x* 1_000_000_000L +y;
}
static final Random random = new Random();
static void sort(int[] a) {
int n = a.length;// shuffle, then sort
for (int i = 0; i < n; i++) {
int oi = random.nextInt(n), temp = a[oi];
a[oi] = a[i];
a[i] = temp;
}
Arrays.sort(a);
}
static void sort(long[] arr) {
shuffleArray(arr);
Arrays.sort(arr);
}
static void shuffleArray(long[] arr) {
int n = arr.length;
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + random.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
}
static class Tuple implements Comparable<Tuple> {
long a;
long b;
long c;
public Tuple(long a, long b) {
this.a = a;
this.b = b;
this.c = 0;
}
public Tuple(long a, long b, long c) {
this.a = a;
this.b = b;
this.c = c;
}
public long getA() { return a; }
public long getB() { return b; }
public long getC() { return c; }
public int compareTo(Tuple other) {
if (this.a == other.a) {
if (this.b == other.b) return Long.compare(this.c, other.c);
return Long.compare(this.b, other.b);
}
return Long.compare(this.a, other.a);
}
@Override
public int hashCode() { return Arrays.deepHashCode(new Long[]{a, b, c}); }
@Override
public boolean equals(Object o) {
if (!(o instanceof Tuple)) return false;
Tuple pairo = (Tuple) o;
return (this.a == pairo.a && this.b == pairo.b && this.c == pairo.c);
}
@Override
public String toString() { return String.format("(%d %d %d) ", this.a, this.b, this.c); }
}
private static int abs(int a){ return (a>=0) ? a: -a; }
private static int min(int... ins){ int min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static int max(int... ins){ int max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static int sum(int... ins){ int total = 0; for (int v : ins) { total += v; } return total; }
private static long abs(long a){ return (a>=0) ? a: -a; }
private static long min(long... ins){ long min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static long max(long... ins){ long max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static long sum(long... ins){ long total = 0; for (long v : ins) { total += v; } return total; }
private static double abs(double a){ return (a>=0) ? a: -a; }
private static double min(double... ins){ double min = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] < min) min = ins[i]; } return min; }
private static double max(double... ins){ double max = ins[0]; for(int i=1; i<ins.length; i++){ if(ins[i] > max) max = ins[i]; } return max; }
private static double sum(double... ins){ double total = 0; for (double v : ins) { total += v; } return total; }
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 2b25cba656c891f17cda507f96d98276 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.util.Scanner;
public class code {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- != 0){
long n = sc.nextLong();
int count =0;
boolean br = false;
while(n != 1){
if(n % 2 == 0){
n /=2;
count++;
}
else if(n % 3 == 0) {
n = (n*2) /3;
count++;
}
else if(n % 5 == 0) {
n = (n*4) /5;
count++;
}
else {
br = true;
break;
}
}
if(br) System.out.println(-1);
else System.out.println(count);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | bd64cfc2296fe785538ea8ab7252c76f | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | // Coded by Vishal Mourya - The Legendary Coder
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.lang.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws java.lang.Exception {
try {
FastReader sc = new FastReader();
long t = sc.nextLong();
while( t-- != 0 ) {
long n = sc.nextLong();
long count = 0;
long r = 0;
while( n != 1) {
if( n % 2 == 0 ) {
n = n/2;
count++;
}
else if( n % 3 == 0 ){
n = (2*n) / 3;
count++;
}
else if( n % 5 == 0 ){
n = (4*n) / 5;
count++;
}
else {
r = 1; break;
}
}
if( r == 0 )
System.out.println(count);
else
System.out.println("-1");
} // end of test case loop
} // End of try block
catch( Exception e ) {
System.out.println( e.getMessage() );
}
} // End of main method
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 4f5b64599b978ec2cae92eb026aa7533 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Bulbs
{
private static int counter = 0;
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
while(n > 0)
{
long a = scanner.nextLong();
int res = func(a);
System.out.println(res);
n--;
}
}
private static int func(long a)
{
if(a == 1)
{
int b = counter;
counter = 0;
return b;
}
else if(a % 2 == 0)
{
counter++;
return func(a / 2);
}
else if(a % 3 == 0)
{
counter++;
return func((2 * a) / 3);
}
else if(a % 5 == 0)
{
counter++;
return func((4 * a )/ 5);
}
else
{
counter = 0;
return -1;
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | a64d81fceb68064a06189600659f9218 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
/**
*
* @author mm887
*/
public class DivideIt {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int cases = input.nextInt();
while(cases-- > 0){
long num = input.nextLong();
long tmp = 0;
int counter = 0;
boolean flag = true;
while(flag){
if(num==1){
flag = false;
}
else if(num%2 == 0){
num = num / 2;
++counter;
}
else if(num%3 == 0){
num = (2*num) / 3;
++counter;
}
else if(num%5 == 0){
num = (4*num) / 5;
++counter;
}
else{
flag = false;
counter = -1;
}
}
if(!flag){
System.out.println(counter);
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 8ddebe06cc63b4dbbaccd077c1969eaa | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Divideit
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
while(tc != 0)
{
long num = sc.nextLong();
int i = 0;
int numofmove = 0;
while(num != 1)
{
if(num % 2 == 0)
{
num /= 2;
numofmove++;
}
else if(num % 3 == 0)
{
num = num*2 /3;
numofmove++;
}
else if(num % 5 == 0)
{
num = num*4 /5;
numofmove++;
}
else
{
numofmove = -1;
break;
}
}
System.out.println(numofmove);
tc--;
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 410990140c3f08a95d0c2d3ba7e93c72 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class A
{
static long n;
static int[] arr;
static String str;
public static void main(String[] args) throws IOException
{
Flash f = new Flash();
int T = f.ni();
for(int tc = 1; tc <= T; tc++){
n = f.nl();
System.out.println(fn());
}
}
static int fn()
{
int ans = 0;
while(n != 1){
long _1 = n, _2 = n, _3 = n;
if(n % 2 == 0) _1 = n/2;
if(n % 3 == 0) _2 = 2*n/3;
if(n % 5 == 0) _3 = 4*n/5;
n = Math.min(_1, Math.min(_2, _3));
if(_1 == n && _2 == n && _3 == n) return -1;
ans++;
}
return ans;
}
static void sort(int[] a){
List<Integer> A = new ArrayList<>();
for(int i : a) A.add(i);
Collections.sort(A);
for(int i = 0; i < A.size(); i++) a[i] = A.get(i);
}
static int swap(int itself, int dummy)
{
return itself;
}
//SecondThread
static class Flash
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next(){
while(!st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine(){
String s = new String();
try{
s = br.readLine().trim();
}catch(IOException e){
e.printStackTrace();
}
return s;
}
//nextInt()
int ni(){
return Integer.parseInt(next());
}
int[] arr(int n){
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = ni();
return a;
}
//nextLong()
long nl(){
return Long.parseLong(next());
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 22391dedbd56fc5a5f12dca2c7859049 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class App
{
public static void main( String[] args )
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
long n = sc.nextLong();
int c = 0;
while(n>1)
{
if(n%2==0)
n = n/2;
else if(n%3==0)
n = 2*n/3;
else if(n%5==0)
n = 4*n/5;
else
break;
c++;
}
if(n==1)
System.out.println(c);
else
System.out.println(-1);
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 80d73052c43d11e6643a78734331a7fd | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main
{
public static void main(String[] args) {
// System.out.println("Hello World");
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
while(t-->0){
long n=scan.nextLong();
int count=0;
while(n!=1){
if(n%2==0){
count++;
n/=2;
}
else if((2*n)%3==0){
count++;
n=(2*n)/3;
}
else if((4*n)%5==0){
count++;
n=(4*n)/5;
} else {
System.out.println("-1");
break;
}
}
if(n==1) System.out.println(count);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | c87890584adc117390c3161d6169bbb4 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.lang.*;
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner s=new Scanner(System.in);
int t=s.nextInt();
while(t!=0)
{
long n=s.nextLong();
int c=0;
while(n>1)
{
if(n%2==0)
{
n=n/2;
c++;
}
else if(n%3==0)
{
n=(2*n)/3;
c++;
}
else if(n%5==0)
{
n=(4*n)/5;
c++;
}
else
{
System.out.println("-1");
break;
}
}
if(n==1)
{
System.out.println(c);
}
t--;
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | a55dd0e0082364750efad80b22ae86cf | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.util.*;import java.io.*;import java.math.*;
public class Main
{
public static void process()throws IOException
{
long n=nl();
long res=0l;
while(n%3==0){
res+=2;
n/=3;
}
while(n%5==0){
res+=3;
n/=5;
}
double temp=Math.log(n)/Math.log(2);
if(temp-(int)temp!=0.0)
pn(-1);
else
pn((long)(temp+res));
}
static AnotherReader sc;
public static void main(String[]args)throws IOException
{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if(oj)
sc=new AnotherReader();
else
sc=new AnotherReader(100);
int t=ni();
while(t-->0)
process();
System.out.flush();
System.out.close();
}
static void pn(Object o){System.out.println(o);}
static void p(Object o){System.out.print(o);}
static void pni(Object o){System.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 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 | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | dcf34a4cce4d1a0b4ec4f005a204d036 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int t=in.nextInt();
while(t-->0)
{
long n=in.nextLong();
int status=0;
long count=0;
while(n!=1)
{
if(n%2==0)
{
count++;
n=n/2;
}
else if(n%3==0)
{
count++;
n=(2*n)/3;
}
else if(n%5==0)
{
count++;
n=(4*n)/5;
}
else
{
status=1;
break;
}
}
if(status==1)
{
System.out.println("-1");
}
else
System.out.println(count);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 55e46dc51216b536c1904476684fa31e | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class cc{
public static void main(String args[])throws Exception{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0){
long n=sc.nextLong();
//int a[]=new int[n];
//int m=a[0];
//for(int i=0;i<n;i++){
// a[i]=sc.nextInt();
// if(a[i]>m)m=a[i];
// }
int s=0;
// for(int i=0;i<n;i++){
// s+=Math.abs(m-a[i]);
//}
int f=0;
while(n>1){
if(n%2==0){
n/=2;
s++;
}
else if(n%3==0)
{
n/=3;
n*=2;
s++;
}
else if(n%5==0){
n/=5;
n*=4;
s++;
}
else{
f=1;
break;
}
}
if(f==0)
System.out.println(s);
else
System.out.println(-1);
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) — the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | e0ba7be44cfc0fad3f819a43a8276be2 | train_000.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.Stack;
import java.util.ArrayList;
import java.util.Vector;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.ArrayDeque;
import java.io.InputStream;
import java.util.HashSet;
import java.util.HashMap;
import java.util.TreeSet;
import java.awt.Point;
public class Z_E {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Autocompletion solver = new Autocompletion();
solver.solve(1, in, out);
out.close();
}
static class Autocompletion {
static int n;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int t=in.nextInt();
for(int z=0;z<t;z++) {
n=in.nextInt();
int m=in.nextInt();
int a=in.nextInt()-1;
int b=in.nextInt()-1;
int c=in.nextInt()-1;
Integer p[]=new Integer[m];
ArrayList<ArrayList<Integer>> next=new ArrayList<ArrayList<Integer>>();
for(int i=0;i<n;i++)next.add(new ArrayList<Integer>());
for(int i=0;i<m;i++)p[i]=in.nextInt();
Arrays.sort(p);
for(int i=0;i<m;i++) {
int d=in.nextInt()-1;
int e=in.nextInt()-1;
next.get(d).add(e);
next.get(e).add(d);
}
long pre[]=new long[m];
pre[0]=p[0];
for(int i=1;i<m;i++)pre[i]=pre[i-1]+p[i];
int[] ad=bfs(a,next);
int[] bd=bfs(b,next);
int[] cd=bfs(c,next);
long best=Long.MAX_VALUE;
for(int i=0;i<n;i++) {
if(ad[i]+bd[i]+cd[i]==0) {
best=0;
}
if(ad[i]+bd[i]+cd[i]>m)continue;
if(bd[i]==0) {
if(ad[i]+cd[i]==0)continue;
best=Math.min(best, pre[ad[i]+cd[i]-1]);
continue;
}
best=Math.min(best, pre[ad[i]+bd[i]+cd[i]-1]+pre[bd[i]-1]);
}
out.println(best);
}
}
private int[] bfs(int a, ArrayList<ArrayList<Integer>> next) {
ArrayDeque<Integer> dq=new ArrayDeque<Integer>();
dq.add(a);
int[] ret=new int[n];
Arrays.fill(ret, Integer.MAX_VALUE);
ret[a]=0;
while(!dq.isEmpty()) {
int x=dq.remove();
for(int b:next.get(x)) {
if(ret[b]>ret[x]+1) {
ret[b]=ret[x]+1;
dq.add(b);
}
}
}
return ret;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| 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 | bd00f06c79570126b039bf1573fbae75 | train_000.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.Queue;
import java.util.StringTokenizer;
public class E {
static ArrayList<ArrayList<Integer>> graph;
static boolean[] vis;
public static void main(String[] args) {
FastReader sc = new FastReader();
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt(), m = sc.nextInt(), a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
long[] p = new long[m + 1];
for (int i = 1; i <= m; i++) p[i] = sc.nextInt();
Arrays.sort(p);
graph = new ArrayList<>();
for (int i = 0; i < n + 1; i++) graph.add(new ArrayList<>());
for (int i = 0; i < m; i++) {
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
long[] dista = dist(a);
long[] distb = dist(b);
long[] distc = dist(c);
// System.out.println(Arrays.toString(dista));
// System.out.println(Arrays.toString(distb));
// System.out.println(Arrays.toString(distc));
for (int i = 1; i <= m; i++) p[i] += p[i - 1];
long res = Long.MAX_VALUE;
for (int x = 1; x <= n; x++) {
long bx = distb[x];
long ox = dista[x] + distc[x];
if (bx + ox > m) continue;
long tot = p[(int) (bx + ox)];
tot += p[(int) bx];
res = Math.min(tot, res);
}
System.out.println(res);
}
}
private static long[] dist(int vertex) {
long[] dist = new long[graph.size()];
vis = new boolean[graph.size()];
dist[vertex] = 0;
vis[vertex] = true;
Queue<Integer> q = new LinkedList<>();
q.add(vertex);
while (!q.isEmpty()) {
int curr = q.poll();
for (int i : graph.get(curr)) {
if (!vis[i]) {
q.add(i);
vis[i] = true;
dist[i] = dist[curr] + 1;
}
}
}
return dist;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["2\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 | 821ebaedde966812fa1b8be638614bf1 | train_000.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.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
StringBuffer out = new StringBuffer();
int t=in.nextInt();
while(t--!=0) {
int n=in.nextInt(),
m=in.nextInt();
int arr[]=new int[3];
for(int i=0; i<3; i++)
arr[i]=in.nextInt();
long price[]=new long[m+1];
for(int i=1; i<=m; i++)
price[i]=in.nextInt();
Arrays.sort(price);
for(int i=1; i<=m; i++)
price[i]+=price[i-1];
LinkedList<Integer> graph[]=new LinkedList[n+1];
for(int i=0; i<=n; i++)
graph[i]=new LinkedList<>();
for(int i=0; i<m; i++) {
int u=in.nextInt(),
v=in.nextInt();
graph[u].add(v);
graph[v].add(u);
}
int travelCost[][]=new int[3][n+1];
for(int i=0; i<3; i++)
bfs(i, arr[i], graph, travelCost);
// System.out.println(Arrays.toString(price));
// for(int i=0; i<3; i++)
// System.out.println(Arrays.toString(travelCost[i]));
long min=Long.MAX_VALUE;
for(int i=1; i<=n; i++) {
long curr=0;
int cnt=0;
for(int j=0; j<3; j++)
cnt+=travelCost[j][i];
if(cnt>m)
continue;
curr=price[cnt]+price[travelCost[1][i]];
// System.out.println(i+" "+curr);
min=Math.min(min, curr);
}
out.append(min+"\n");
}
System.out.println(out);
}
public static void bfs(int index, int start, LinkedList<Integer> graph[], int travelCost[][]) {
Arrays.fill(travelCost[index], -1);
travelCost[index][start]=0;
Queue<Integer> q=new LinkedList<>();
q.add(start);
while(!q.isEmpty()) {
int size=q.size();
while(size--!=0) {
int poll=q.poll();
for(int item: graph[poll]) if(travelCost[index][item]==-1) {
travelCost[index][item]=travelCost[index][poll]+1;
q.add(item);
}
}
}
}
}
| 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 | 3e29c313a0516b06b596548459fd1e27 | train_000.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.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
public class B {
public static int n, a, b, c, m;
public static ArrayList<Integer>[] adj;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
InputReader s = new InputReader(System.in);
PrintWriter p = new PrintWriter(System.out);
int t = s.nextInt();
while (t-- > 0) {
n = s.nextInt();
m = s.nextInt();
a = s.nextInt() - 1;
b = s.nextInt() - 1;
c = s.nextInt() - 1;
adj = new ArrayList[n];
ArrayList<Long> price = new ArrayList<>();
for (int i = 0; i < n; i++)
adj[i] = new ArrayList<>();
for (int i = 0; i < m; i++)
price.add(s.nextLong());
Collections.sort(price);
for (int i = 0; i < m; i++) {
int src = s.nextInt() - 1;
int dest = s.nextInt() - 1;
adj[src].add(dest);
adj[dest].add(src);
}
long[] prefix = new long[m + 1];
for (int i = 0; i < m; i++) {
prefix[i + 1] += (long) prefix[i] + (long) price.get(i);
}
int[] arr1 = bfs(a);
int[] arr2 = bfs(b);
int[] arr3 = bfs(c);
// for (int i = 0; i < n; i++) {
// p.print(arr1[i] + " ");
// }
// p.println();
// for (int i = 0; i < n; i++) {
// p.print(arr2[i] + " ");
// }
// p.println();
// for (int i = 0; i < n; i++) {
// p.print(arr3[i] + " ");
// }
// p.println();
long ans = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
long temp2 = arr1[i] + arr2[i] + arr3[i];
if (arr1[i] + arr2[i] + arr3[i] <= m) {
long temp = prefix[arr2[i]] + prefix[arr1[i] + arr2[i] + arr3[i]];
ans = Math.min(temp, ans);
}
}
p.println(ans);
}
p.flush();
p.close();
}
public static int[] bfs(int node) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = Integer.MAX_VALUE;
int[] vis = new int[n];
arr[node] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(node);
vis[node] = 1;
while (!q.isEmpty()) {
int curr = q.poll();
for (int i = 0; i < adj[curr].size(); i++) {
int nbr = adj[curr].get(i);
arr[nbr] = Math.min(arr[nbr], arr[curr] + 1);
if (vis[nbr] == 0) {
vis[nbr] = 1;
q.add(nbr);
}
}
}
return arr;
}
public static long GCD(long a, long b) {
if (b == 0)
return a;
else
return GCD(b, a % b);
}
public static long LCM(long a, long b) {
return (a * b) / GCD(a, b);
}
static class pair implements Comparable<pair> {
Integer x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if (result == 0)
result = y.compareTo(o.y);
return result;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x - x == 0 && p.y - y == 0;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
}
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);
}
}
static class CodeX {
public static void sort(long arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(long A[], long start, long end) {
if (start < end) {
long mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(long A[], long start, long mid, long end) {
long p = start, q = mid + 1;
long Arr[] = new long[(int) (end - start + 1)];
long k = 0;
for (int i = (int) start; i <= end; i++) {
if (p > mid)
Arr[(int) k++] = A[(int) q++];
else if (q > end)
Arr[(int) k++] = A[(int) p++];
else if (A[(int) p] < A[(int) q])
Arr[(int) k++] = A[(int) p++];
else
Arr[(int) k++] = A[(int) q++];
}
for (int i = 0; i < k; i++) {
A[(int) start++] = Arr[i];
}
}
}
} | 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 | a70e44d41cf70432c9a79aabb0fcdef2 | train_000.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.io.FileReader;
import java.util.Queue;
import java.util.LinkedList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
EWeightsDistributing solver = new EWeightsDistributing();
solver.solve(1, in, out);
out.close();
}
static class EWeightsDistributing {
int n;
int m;
int a;
int b;
int c;
int[] prices;
ArrayList<Integer>[] adjL;
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int q = sc.nextInt();
while (q-- > 0) {
pw.println(solve(sc));
}
}
private long solve(Scanner sc) {
n = sc.nextInt();
m = sc.nextInt();
a = sc.nextInt() - 1;
b = sc.nextInt() - 1;
c = sc.nextInt() - 1;
prices = new int[m];
for (int i = 0; i < m; i++)
prices[i] = sc.nextInt();
shuffle(prices);
Arrays.sort(prices);
adjL = new ArrayList[n];
for (int i = 0; i < n; i++)
adjL[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
adjL[u].add(v);
adjL[v].add(u);
}
int[] Adist = bfs(a), Bdist = bfs(b), Cdist = bfs(c);
long[] prefix = new long[m];
for (int i = 0; i < m; i++) {
prefix[i] = prices[i];
if (i > 0)
prefix[i] += prefix[i - 1];
}
long min = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
int toB = Bdist[i];
long toBPrefix = 0;
long temp = 0;
if (toB > 0)
toBPrefix = prefix[toB - 1];
temp += 2 * toBPrefix;
int toA = Adist[i];
int toC = Cdist[i];
if (toA + toC + toB - 1 < m && toA + toC + toB - 1 >= 0)
temp += prefix[toA + toC + toB - 1] - toBPrefix;
else if (toA + toC + toB - 1 >= m)
continue;
min = Math.min(min, temp);
}
return min;
}
private int[] bfs(int s) {
int[] dist = new int[n];
Arrays.fill(dist, (int) 1e9);
dist[s] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while (!q.isEmpty()) {
int cur = q.poll();
for (int v : adjL[cur]) {
if (dist[v] > dist[cur] + 1) {
dist[v] = dist[cur] + 1;
q.add(v);
}
}
}
return dist;
}
private void shuffle(int[] prices) {
for (int i = 0; i < prices.length; i++) {
int rand = (int) (Math.random() * (i + 1));
int temp = prices[rand];
prices[rand] = prices[i];
prices[i] = temp;
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| 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 | 07ddc8303dfa8bb14ab8224a0c6846ba | train_000.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 | /**
* The author of the following code is - Dewansh Nigam
* Username - dewanshnigam
* Unstoppable Now.
*/
import java.util.*;
import java.io.*;
public class Codeforces_NewBie_ProblemE
{
static InputReader in=new InputReader(System.in);
static OutputWriter out=new OutputWriter(System.out);
static StringBuilder sb=new StringBuilder();
static long MOD = (long)(1e9+7);
static final int INF = Integer.MAX_VALUE;
static final long INFL = Long.MAX_VALUE;
// Main Class Starts Here
public static void main(String args[])throws IOException
{
// Write your code.
int t = in();
while(t-->0) {
int n=in();
int m=in();
int a=in();
int b=in();
int c=in();
int p[]=an(m);
Graph graph = new Graph(n,m);
for(int i=0;i<m;i++) {
int u = in();
int v = in();
--u;
--v;
graph.addEdge(u, v);
}
long ans = graph.shortestPath(a, b, c, p);
app(ans+"\n");
}
out.printLine(sb);
out.close();
}
static class Graph
{
int n;
int m;
Node nd[];
public Graph(int n, int m) {
this.n = n;
this.m = m;
nd = new Node[n];
for(int i=0; i<n;i++) {
nd[i] = new Node(i);
}
}
public void addEdge(int u,int v) {
nd[u].ne.add(v);
nd[v].ne.add(u);
}
public int[] bfs(int src) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(src);
int dist[] = new int[n];
Arrays.fill(dist, INF);
dist[src] = 0;
while(!q.isEmpty()) {
int index = q.poll();
for(int adj : nd[index].ne) {
if(dist[adj] == INF) {
dist[adj] = dist[index]+1;
q.add(adj);
}
}
}
return dist;
}
public long shortestPath(int a,int b,int c,int p[]) {
Arrays.sort(p);
long prefix[] = new long[m+1];
int k=1;
for(int x:p) {
prefix[k++] = (long)x;
}
for(int i=1;i<prefix.length;i++) {
prefix[i] += prefix[i-1];
}
a--;b--;c--;
int distA[] = bfs(a);
int distB[] = bfs(b);
int distC[] = bfs(c);
long min = INFL;
for(int i=0; i < n;i++) {
int A = distA[i];
int B = distB[i];
int C = distC[i];
if( (A+B+C) > m )
continue;
long alt = prefix[ A + B + C] + prefix[ B ];
min = Math.min(min, alt);
}
return min;
}
}
static class Node
{
int index;
Vector<Integer> ne;
public Node(int index) {
this.index = index;
ne = new Vector<>();
}
}
public static int[] an(int n) {
int ar[]=new int[n];
for(int i=0;i<n;i++)
ar[i]=in();
return ar;
}
public static int in() {
return in.readInt();
}
public static void prln(String str) {
out.printLine(str);
}
public static long lin() {
return in.readLong();
}
public static String sn() {
return in.readString();
}
public static HashMap<Integer,Integer> hm(int a[]){
HashMap<Integer,Integer> map=new HashMap<>();
for(int i=0; i < a.length;i++) {
int keep = (int)map.getOrDefault(a[i],0);
map.put(a[i],++keep);
}
return map;
}
public static void app(Object o) {
sb.append(o);
}
public static void display(int a[]) {
prln(Arrays.toString(a));
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int 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 long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String 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);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.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 | f9ddd9db0b18d5a9798960468e8ecb8b | train_000.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 | /*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
public class GFG {
static int n,m,a,b,c;
static ArrayList<ArrayList<Integer>> edges=new ArrayList<>();
static int[] solveUtil(int a)
{
Queue<Integer> queue=new LinkedList<>();
queue.add(a);
boolean vis[]=new boolean[n+1];
vis[a]=true;
int dist[]=new int[n+1];
dist[a]=0;
while(!queue.isEmpty())
{
int u=queue.peek();
queue.remove();
for(int v:edges.get(u))
{
if(!vis[v])
{
vis[v]=true;
queue.add(v);
dist[v]=dist[u]+1;
}
}
}
return dist;
}
static long solve(Long p[])
{
int []ad=solveUtil(a);
int []bd=solveUtil(b);
int []cd=solveUtil(c);
long cost=Long.MAX_VALUE;
for(int d=1;d<=n;d++)
{
int id=ad[d]+bd[d]+cd[d];
int ext=bd[d];
if(id>m)
continue;
cost=Math.min(cost,p[id]+p[ext]);
}
return cost;
}
public static void main (String[] args) throws Exception{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(bf.readLine());
StringBuffer str=new StringBuffer("");
while(t-->0)
{
edges.clear();
String s[]=bf.readLine().trim().split("\\s+");
n=Integer.parseInt(s[0]);
m=Integer.parseInt(s[1]);
a=Integer.parseInt(s[2]);
b=Integer.parseInt(s[3]);
c=Integer.parseInt(s[4]);
Long p[]=new Long[m+1];
p[0]=0L;
s=bf.readLine().trim().split("\\s+");
for(int i=1;i<=m;i++)
p[i]=Long.parseLong(s[i-1]);
for(int i=0;i<=n;i++)
edges.add(new ArrayList<>());
Arrays.sort(p);
for(int i=1;i<=m;i++)
p[i]+=p[i-1];
for(int i=0;i<m;i++)
{
s=bf.readLine().trim().split("\\s+");
int x=Integer.parseInt(s[0]),y=Integer.parseInt(s[1]);
edges.get(x).add(y);
edges.get(y).add(x);
}
str.append(solve(p)+"\n");
}
System.out.println(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 | 8a81484429c48d27a6fba2fc6d7e68ec | train_000.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 Solution implements Runnable{
FastScanner sc;
PrintWriter pw;
final class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
public long nlo() {
return Long.parseLong(next());
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public String nli() {
String line = "";
if (st.hasMoreTokens()) line = st.nextToken();
else try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
while (st.hasMoreTokens()) line += " " + st.nextToken();
return line;
}
public double nd() {
return Double.parseDouble(next());
}
}
public static void main(String[] args)
{
new Thread(null,new Solution(),"codeforces",1<<25).start();
}
public void run()
{
sc=new FastScanner();
pw=new PrintWriter(System.out);
solve();
pw.flush();
pw.close();
}
public long gcd(long a,long b)
{
return b==0L?a:gcd(b,a%b);
}
public long ppow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
public int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
//////////////////////////////////
///////////// LOGIC ///////////
////////////////////////////////
public void solve(){
int t=sc.ni();
while(t-->0){
int n=sc.ni();
int m=sc.ni();
int a=sc.ni()-1;
int b=sc.ni()-1;
int c=sc.ni()-1;
Long[] mrr=new Long[m];
for(int i=0;i<m;i++)
mrr[i]=sc.nlo();
Arrays.sort(mrr);
for(int i=1;i<m;i++)
mrr[i]+=mrr[i-1];
ArrayList<Integer>[] adj=new ArrayList[n];
for(int i=0;i<n;i++)
adj[i]=new ArrayList();
int[] visit=new int[n];
int[] prr=new int[n];
for(int i=0;i<m;i++)
{
int x=sc.ni()-1;
int y=sc.ni()-1;
adj[x].add(y);
adj[y].add(x);
}
int[] arr=new int[n];
int[] brr=new int[n];
int[] crr=new int[n];
Arrays.fill(visit,0);
bfs(a,visit,adj,arr);
Arrays.fill(visit,0);
bfs(b,visit,adj,brr);
Arrays.fill(visit,0);
bfs(c,visit,adj,crr);
long ans=Long.MAX_VALUE;
for(int i=0;i<n;i++)
{
if(arr[i]+brr[i]+crr[i]<=m)
{
long d1=0,d2=0;
if(brr[i]!=0)
d2=mrr[brr[i]-1];
if(arr[i]+brr[i]+crr[i]>0)
d1=mrr[arr[i]+brr[i]+crr[i]-1];
ans=Math.min(ans,d1+d2);
}
}
pw.println(ans);
}
}
public void bfs(int x,int[] visit,ArrayList<Integer>[] adj,int[] dist)
{
Queue<Integer> q=new ArrayDeque();
visit[x]=1;
q.add(x);
dist[x]=0;
while(!q.isEmpty())
{
x=q.poll();
for(int y:adj[x])
{
if(visit[y]==0)
{
visit[y]=1;
dist[y]=dist[x]+1;
q.add(y);
}
}
}
}
}
| 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 | 304df5fb5ae0f5f1e3d76688ac46871a | train_000.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 | // package Div3_636;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class ProblemE {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int test=Integer.parseInt(br.readLine());
StringBuilder print=new StringBuilder();
while(test--!=0){
StringTokenizer st=new StringTokenizer(br.readLine());
int 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());
ArrayList<Integer> graph[]=new ArrayList[n+1];
for(int i=1;i<=n;i++){
graph[i]=new ArrayList<>();
}
ArrayList<Integer> prices=new ArrayList<>();
st=new StringTokenizer(br.readLine());
for(int i=1;i<=m;i++){
prices.add(Integer.parseInt(st.nextToken()));
}
for(int i=1;i<=m;i++){
st=new StringTokenizer(br.readLine());
int u=Integer.parseInt(st.nextToken());
int v=Integer.parseInt(st.nextToken());
graph[u].add(v);graph[v].add(u);
}
Collections.sort(prices);
long prefix[]=new long[m+1];
for(int i=1;i<=m;i++){
prefix[i]=prefix[i-1]+prices.get(i-1);
}
int deptha[]=new int[n+1];
int depthb[]=new int[n+1];
int depthc[]=new int[n+1];
bfs(graph,a,deptha);
bfs(graph,b,depthb);
bfs(graph,c,depthc);
long ans=Long.MAX_VALUE;
if(deptha[b]+depthb[c]<=m){
int len=deptha[b]+depthb[c];
ans=prefix[len];
}
for(int i=1;i<=n;i++){
if(deptha[i]+depthb[i]+depthc[i]<=m){
int overlap=depthb[i];
long temp=2*prefix[overlap];
int rem=deptha[i]+depthc[i];
int total=overlap+rem;
temp+=prefix[total]-prefix[overlap];
ans=Math.min(ans,temp);
}
}
print.append(ans+"\n");
}
System.out.print(print.toString());
}
public static void bfs(ArrayList<Integer> graph[],int a,int depth[]){
boolean visited[]=new boolean[depth.length];
Queue<Integer> queue=new LinkedList<>();
queue.add(a);
visited[a]=true;
while (!queue.isEmpty()){
int curr=queue.remove();
for(int j:graph[curr]){
if(!visited[j]){
depth[j]=depth[curr]+1;
queue.add(j);
visited[j]=true;
}
}
}
}
}
| 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 | 5b4c2350c9cd936298265d54216f3ee1 | train_000.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.Queue;
import java.util.StringTokenizer;
public class E {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws IOException {
BufferedReader file = new BufferedReader(new InputStreamReader(System.in));
int inputs = Integer.parseInt(file.readLine());
while(inputs-->0) {
StringTokenizer st = new StringTokenizer(file.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
int c = Integer.parseInt(st.nextToken())-1;
Integer[] prices = new Integer[m];
st = new StringTokenizer(file.readLine());
for(int i = 0; i < m; i++) {
prices[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(prices);
long[] preSum = new long[m+1];
for(int i = 0; i < m; i++) {
preSum[i+1] += preSum[i] + prices[i];
}
ArrayList<Integer>[] con = new ArrayList[n];
for(int i = 0; i < n; i++) {
con[i] = new ArrayList<>();
}
for(int i = 0; i < m; i++) {
st = new StringTokenizer(file.readLine());
int e = Integer.parseInt(st.nextToken())-1;
int f = Integer.parseInt(st.nextToken())-1;
con[e].add(f);
con[f].add(e);
}
int[] aDist = new int[n];
int[] bDist = new int[n];
int[] cDist = new int[n];
bfs(a, con, aDist);
bfs(b, con, bDist);
bfs(c, con, cDist);
long min = Long.MAX_VALUE;
for(int i = 0; i < n; i++) {
if(aDist[i]+bDist[i]+cDist[i] <= m)
min = Math.min(min, preSum[bDist[i]]+preSum[aDist[i]+bDist[i]+cDist[i]]);
}
System.out.println(min);
}
}
public static void bfs(int start, ArrayList<Integer>[] con, int[] dist) {
boolean[] vis = new boolean[con.length];
Queue<int[]> nodes = new LinkedList<>();
nodes.add(new int[] {start, 0});
while(!nodes.isEmpty()) {
int[] curr = nodes.remove();
if(vis[curr[0]])
continue;
vis[curr[0]] = true;
dist[curr[0]] = curr[1];
for(int i : con[curr[0]]) {
if(!vis[i])
nodes.add(new int[] {i, curr[1]+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 | 7be64991c898ab6fe0259cfdb8cf504f | train_000.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.InputStream;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.*;
import java.io.*;
import java.lang.*;
public class Main{
public static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.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);
}
}
static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a*b)/gcd(a, b);
}
public static void sortbyColumn(int arr[][], int col)
{
Arrays.sort(arr, new Comparator<int[]>() {
@Override
public int compare(final int[] entry1,
final int[] entry2) {
if (entry1[col] > entry2[col])
return 1;
else
return -1;
}
});
}
static long func(long a[],long size,int s){
long max1=a[s];
long maxc=a[s];
for(int i=s+1;i<size;i++){
maxc=Math.max(a[i],maxc+a[i]);
max1=Math.max(maxc,max1);
}
return max1;
}
public static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
public U x;
public V y;
public Pair(U x, V y) {
this.x = x;
this.y = y;
}
public int hashCode() {
return (x == null ? 0 : x.hashCode() * 31) + (y == null ? 0 : y.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (x == null ? p.x == null : x.equals(p.x)) && (y == null ? p.y == null : y.equals(p.y));
}
public int compareTo(Pair<U, V> b) {
int cmpU = x.compareTo(b.x);
return cmpU != 0 ? cmpU : y.compareTo(b.y);
}
public String toString() {
return String.format("(%s, %s)", x.toString(), y.toString());
}
}
static LinkedList<Integer> li[]=new LinkedList[100001];
static int ans1=0,ans2=0,max1=-1;
static int dist[]=new int[100001];
static int visited[]=new int[100001];
//static int arr[];
static ArrayList<Integer> adj[];
static void bfs(int n,int m){
//visited[x]=1;
//visit[j]++;
dist[n]=0;
visited[n]=1;
Queue<Integer> q=new LinkedList<>();
q.add(n);
while(!q.isEmpty()){
int x=q.poll();
for(int i=0;i<adj[x].size();i++){
if(visited[adj[x].get(i)]==0){
q.add(adj[x].get(i));
visited[adj[x].get(i)]=1;
dist[adj[x].get(i)]=dist[x]+1;
}
if(adj[x].get(i)==m)
{
return;
}
}
}
// for(int i=0;i<adj[x].size();i++){
// if(visited[adj[x].get(i)]==0){
// //check[j]++;
// ans1++;
// dfs(adj[x].get(i));
// }
// }
}
static void bfs(int dist[],int start){
dist[start]=0;
Queue<Integer> q=new LinkedList<>();
q.add(start);
while(!q.isEmpty()){
int x=q.poll();
for(int i : adj[x]){
if(dist[x]+1<dist[i]){
dist[i]=dist[x]+1;
q.add(i);
}
}
}
}
public static void main(String args[]){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter w = new PrintWriter(outputStream);
int t=in.nextInt(),i,j,k;
for(i=0;i<t;i++){
int n,m,a,b,c;
n=in.nextInt();
m=in.nextInt();
a=in.nextInt()-1;
b=in.nextInt()-1;
c=in.nextInt()-1;
long arr[]=new long[m];
int distA[]=new int[n];
int distB[]=new int[n];
int distC[]=new int[n];
adj=new ArrayList[n];
for(j=0;j<n;j++){
adj[j]=new ArrayList<>();
distA[j]=distB[j]=distC[j]=Integer.MAX_VALUE;
}
for(j=0;j<m;j++){
arr[j]=in.nextLong();
}
for(j=0;j<m;j++){
int u,v;
u=in.nextInt()-1;
v=in.nextInt()-1;
adj[u].add(v);
adj[v].add(u);
}
Arrays.sort(arr);
for(j=1;j<m;j++){
arr[j]+=arr[j-1];
}
bfs(distA,a);
bfs(distB,b);
bfs(distC,c);
long ans=Long.MAX_VALUE;
for(j=0;j<n;j++){
int ori=distB[j],other=distA[j]+distC[j],bet=ori+other;
if(bet>m){
continue;
}
long cur;
if(ori==0){
cur=0;
}else{
cur=arr[ori-1];
}
cur*=2;
if(bet-1<0){
cur+=0;
}else{
if(ori==0){
cur+=arr[bet-1];
}else{
cur+=arr[bet-1]-arr[ori-1];
}
}
ans=Math.min(cur,ans);
}
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 | 9f37ed6ea87b5ff80f5f17edb8fbd628 | train_000.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 Solution {
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.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 addd) {
addd.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static FastReader sc = new FastReader();
static int mod = (int) (1e9+7),MAX=(int) (1e6+100);
static List<Integer>[] edges ;
public static void main(String[] args) {
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
int m = sc.nextInt();
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
Long[] cost = new Long[m+1];
cost[0] = 0L;
for(int i=1;i<=m;++i) cost[i] = sc.nextLong();
Arrays.sort(cost);
for(int i=1;i<=m;++i) cost[i]+=cost[i-1];
edges = new ArrayList[n+1];
for(int i=0;i<edges.length;++i) edges[i] = new ArrayList<>();
for(int i=1;i<=m;++i) {
int u = sc.nextInt();
int v = sc.nextInt();
edges[u].add(v);
edges[v].add(u);
}
int[] disa = new int[n+1]; Arrays.fill(disa,Integer.MAX_VALUE/10);
int[] disb = new int[n+1]; Arrays.fill(disb,Integer.MAX_VALUE/10);
int[] disc = new int[n+1]; Arrays.fill(disc,Integer.MAX_VALUE/10);
bfs(a,disa); bfs(b,disb); bfs(c,disc);
long ans = Long.MAX_VALUE;
// for max comm path a->b->c
for(int x=1;x<=n;++x) { // assume it to be LCA type node
if(disa[x] + disb[x] + disc[x] > m) continue;
long sum = cost[disb[x]] + cost[disa[x] + disb[x] + disc[x]];
ans = Math.min(ans, sum);
}
out.println(ans);
}
out.close();
}
private static void bfs(int v, int[] dis) {
dis[v] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(v);
while(q.size() > 0) {
int x = q.poll();
for(int node : edges[x]) {
if(dis[node] == Integer.MAX_VALUE/10) {
dis[node] = dis[x] + 1;
q.add(node);
}
}
}
}
}
| 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 | 14324fc6f9b9fc4cdfc7c4415c8481a1 | train_000.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.*;
public class ProblemE {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
long T=scn.nextLong();
for(int t=0;t<T;t++){
int N=scn.nextInt();
int M=scn.nextInt();
int a=scn.nextInt();
int b=scn.nextInt();
int c=scn.nextInt();
long[] P=new long[M+1];
for(int i=1;i<=M;i++){
P[i]=scn.nextLong();
}
Arrays.sort(P);
long[] prefx=new long[M+1];
for(int i=1;i<=M;i++){
prefx[i]=prefx[i-1]+P[i];
}
List<List<Integer>> adjList=new ArrayList<>();
for(int i=0;i<=N;i++){
adjList.add(i, new ArrayList<>());
}
int x, y;
for(int i=0;i<M;i++){
x=scn.nextInt();
y=scn.nextInt();
adjList.get(x).add(y);
adjList.get(y).add(x);
}
int[] A;
int[] B;
int[] C;
A=shortestDistance(adjList, a);
B=shortestDistance(adjList, b);
C=shortestDistance(adjList, c);
Long sum=Long.MAX_VALUE;
for(int i=1;i<=N;i++){
if(A[i]+B[i]+C[i]<=M){
sum=Math.min(sum, prefx[A[i]+B[i]+C[i]]+prefx[B[i]]);
}
}
System.out.println(sum);
}
}
private static int[] shortestDistance(List<List<Integer>> adjList, int a) {
int[] A=new int[adjList.size()];
boolean[] visited=new boolean[A.length];
Queue<Integer> queue=new LinkedList<>();
queue.add(a);
int x,y;
while (!queue.isEmpty()){
y=queue.poll();
visited[y]=true;
Iterator<Integer> iterator=adjList.get(y).iterator();
while (iterator.hasNext()){
x=iterator.next();
if(!visited[x]){
A[x]=A[y]+1;
queue.add(x);
visited[x]=true;
}
}
}
return A;
}
}
| 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 | c1ea5f0ddb38d47ebd8c4338a1431aac | train_000.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.*;
public class C636E
{
static class Edge implements Comparator<Edge>
{
int i;
int d;
public Edge()
{
}
public Edge(int i,int d)
{
this.i=i;
this.d=d;
}
public int compare(Edge a,Edge b)
{
if(b.d>a.d)
{
return 1;
}
else
{
return -1;
}
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int m=sc.nextInt();
int s=sc.nextInt()-1;
int t1=sc.nextInt()-1;
int f=sc.nextInt()-1;
long ar[]=new long[m];
for(int x=0;x<m;x++)
{
ar[x]=sc.nextInt();
}
Arrays.sort(ar);
long pre[]=new long[m+1];
for(int x=0;x<m;x++)
{
pre[x+1]=pre[x]+ar[x];
}
LinkedList graph[]=new LinkedList[n];
for(int x=0;x<n;x++)
{
graph[x]=new LinkedList<Integer>();
}
for(int x=0;x<m;x++)
{
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
graph[a].add(b);
graph[b].add(a);
}
int d1[]=solve(graph,n,s);
int d2[]=solve(graph,n,t1);
int d3[]=solve(graph,n,f);
long ans=Long.MAX_VALUE;
for(int x=0;x<n;x++)
{
if(d1[x]+d2[x]+d3[x]<=m)
{
long c=(long)pre[d2[x]] + pre[d1[x] + d2[x] + d3[x]];
if(c<ans)
{
ans=c;
}
}
}
System.out.println(ans);
}
}
public static int[] solve(LinkedList graph[],int n,int s)
{
int d[]=new int[n];
for(int x=0;x<n;x++)
{
d[x]=Integer.MAX_VALUE;
}
d[s] = 0;
Queue<Integer> q=new LinkedList<Integer>();
q.add(s);
while(!q.isEmpty())
{
int v = q.poll();
Iterator<Integer> itr=graph[v].iterator();
while(itr.hasNext())
{
int u=itr.next();
if (d[u] == Integer.MAX_VALUE)
{
d[u]=d[v]+1;
q.add(u);
}
}
}
return d;
}
} | 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 | bb521ba368dd49c3420da3642f90c872 | train_000.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 E
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok;
ArrayList<Long> inCosts, outCosts;
public void go() throws IOException {
StringTokenizer tok = new StringTokenizer(in.readLine());
int zzz = Integer.parseInt(tok.nextToken());
for (int zz = 0; zz < zzz; zz++)
{
ntok();
int n = ipar();
int m = ipar();
int a = ipar()-1;
int b = ipar()-1;
int c = ipar()-1;
Vertex[] vertices = new Vertex[n];
ntok();
long[] allCosts = lapar(m);
for (int i = 0; i < n; i++) {
vertices[i] = new Vertex(i);
}
sort(allCosts);
long[] prefix = new long[m+1];
for (int i = 0; i < m; i++) {
prefix[i+1] = prefix[i] + allCosts[i];
}
for (int i = 0; i < m; i++) {
ntok();
int u = ipar()-1;
int v = ipar()-1;
Edge e = new Edge(vertices[u], vertices[v]);
vertices[u].edges.add(e);
vertices[v].edges.add(e);
}
int[][] dists = new int[3][n];
bfs(vertices[a], dists[0]);
bfs(vertices[b], dists[1]);
bfs(vertices[c], dists[2]);
long best = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
int ones = dists[0][i] + dists[2][i];
int twos = dists[1][i];
if (ones + twos > m) {
continue;
}
best = Math.min(best, prefix[ones + twos] + prefix[twos]);
}
out.println(best);
}
out.flush();
in.close();
}
public void bfs(Vertex start, int[] dist) {
LinkedList<Vertex> queue = new LinkedList<>();
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start.i] = 0;
queue.add(start);
while (!queue.isEmpty()) {
Vertex curr = queue.remove();
for (Edge e : curr.edges) {
Vertex other = e.other(curr);
if (dist[curr.i] + 1 < dist[other.i]) {
dist[other.i] = dist[curr.i]+1;
queue.add(other);
}
}
}
}
// public void go() throws IOException
// {
// StringTokenizer tok = new StringTokenizer(in.readLine());
// int zzz = Integer.parseInt(tok.nextToken());
// for (int zz = 0; zz < zzz; zz++)
// {
// ntok();
// int n = ipar();
// int m = ipar();
// int a = ipar()-1;
// int b = ipar()-1;
// int c = ipar()-1;
// Vertex[] vertices = new Vertex[n];
// ntok();
// long[] allCosts = lapar(m);
// for (int i = 0; i < n; i++) {
// vertices[i] = new Vertex(i);
// vertices[i].dist = Long.MAX_VALUE;
// }
// sort(allCosts);
// for (int i = 0; i < m; i++) {
// ntok();
// int u = ipar()-1;
// int v = ipar()-1;
// Edge e = new Edge(vertices[u], vertices[v]);
// vertices[u].edges.add(e);
// vertices[v].edges.add(e);
// }
// vertices[a].dist = 0;
// LinkedList<Vertex> queue = new LinkedList<>();
// queue.add(vertices[a]);
// while (!queue.isEmpty()) {
// Vertex curr = queue.remove();
// if (curr.i == b) {
// break;
// }
// for (Edge e : curr.edges) {
// Vertex other = e.other(curr);
// if (curr.dist + 1 < other.dist) {
// other.prev = e;
// other.dist = curr.dist + 1;
// queue.add(other);
// }
// }
// }
// int numInPath = markPath(vertices[b]);
// inCosts = new ArrayList<>();
// outCosts = new ArrayList<>();
// inCosts.add(0L);
// outCosts.add(0L);
// long sum = 0;
// for (int i = 0; i < numInPath; i++) {
// sum += allCosts[i];
// inCosts.add(sum);
// }
// sum = 0;
// for (int i = numInPath; i < m; i++) {
// sum += allCosts[i];
// outCosts.add(sum);
// }
// out.println(inCosts);
// out.println(outCosts);
// out.println(numInPath + " " + inCosts.get(inCosts.size()-1));
// TreeSet<Vertex> pq = new TreeSet<>();
// for (Vertex v : vertices) {
// v.dist = Long.MAX_VALUE;
// pq.add(v);
// }
// pq.remove(vertices[b]);
// vertices[b].dist = 0;
// pq.add(vertices[b]);
// while (!pq.isEmpty()) {
// Vertex curr = pq.first();
// curr.visited = true;
// if (curr.i == c) {
// break;
// }
// pq.remove(curr);
// for (Edge e : curr.edges) {
// Vertex other = e.other(curr);
// if (other.visited) {
// continue;
// }
// long nextVal = inCosts.get(curr.inCount + (e.chosen ? 1 : 0)) + outCosts.get(curr.outCount + (e.chosen ? 0 : 1));
// if (nextVal < other.dist) {
// pq.remove(other);
// other.dist = nextVal;
// other.inCount = curr.inCount + (e.chosen ? 1 : 0);
// other.outCount = curr.outCount + (e.chosen ? 0 : 1);
// pq.add(other);
// }
// }
// }
// out.println(inCosts.get(inCosts.size()-1) + vertices[c].dist);
// }
// out.flush();
// in.close();
// }
public int markPath(Vertex end) {
int count = 0;
while (end.prev != null) {
count++;
Edge e = end.prev;
e.chosen = true;
end = e.other(end);
}
return count;
}
public void sort(long[] arr) {
ArrayList<Long> list = new ArrayList<>();
for (long x : arr) {
list.add(x);
}
Collections.sort(list);
for (int i = 0; i < arr.length; i++) {
arr[i] = list.get(i);
}
}
private class Vertex implements Comparable<Vertex> {
int i;
int inCount, outCount;
ArrayList<Edge> edges;
long dist;
boolean visited, inPath;
Edge prev;
public Vertex(int i) {
this.i = i;
edges = new ArrayList<>();
}
public int compareTo(Vertex other) {
if (dist == other.dist) {
return Integer.compare(i, other.i);
}
return Long.compare(dist, other.dist);
}
}
private class Edge {
boolean chosen;
Vertex a, b;
boolean ab, ac, bc;
public Edge(Vertex a, Vertex b) {
this.a = a;
this.b = b;
}
public Vertex other(Vertex v) {
return v == a ? b : a;
}
}
public void ntok() throws IOException
{
tok = new StringTokenizer(in.readLine());
}
public int ipar()
{
return Integer.parseInt(tok.nextToken());
}
public int[] iapar(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = ipar();
}
return arr;
}
public long lpar()
{
return Long.parseLong(tok.nextToken());
}
public long[] lapar(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = lpar();
}
return arr;
}
public double dpar()
{
return Double.parseDouble(tok.nextToken());
}
public String spar()
{
return tok.nextToken();
}
public static void main(String[] args) throws IOException
{
new E().go();
}
}
| 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 | a3c0e761e0217bb9a206c988a3234c4d | train_000.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 | /**
* BaZ :D
*/
import java.text.DecimalFormat;
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class ACMIND
{
static FastReader scan;
static PrintWriter pw;
static long MOD = 1_000_000_007;
static long INF = 2_000_000_000_000_000_000L;
static long inf = 2_000_000_000;
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<27)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static int n,m,a,b,c;
static ArrayList<Integer> adj[];
static Integer weights[];
static long pref[];
static void solve() throws IOException {
scan = new FastReader();
pw = new PrintWriter(System.out, true);
StringBuilder sb = new StringBuilder();
int t = ni();
while (t-->0) {
n = ni();
m = ni();
a = ni();
b = ni();
c = ni();
adj = new ArrayList[n+1];
for(int i=1;i<=n;++i) {
adj[i] = new ArrayList<>();
}
weights = new Integer[m];
for(int i=0;i<m;++i) {
weights[i] = ni();
}
Arrays.sort(weights);
pref = new long[m+1];
for(int i=1;i<=m;++i) {
pref[i]+=weights[i-1];
pref[i]+=pref[i-1];
}
for(int i=0;i<m;++i) {
int u = ni(), v = ni();
adj[u].add(v);
adj[v].add(u);
}
int a_dis[] = BFS(a);
//pa("a_dis", a_dis);
int b_dis[] = BFS(b);
//pa("b_dis", b_dis);
int c_dis[] = BFS(c);
//pa("c_dis", c_dis);
long ans = Long.MAX_VALUE;
for(int i=1;i<=n;++i) {
if(a_dis[i] + c_dis[i] + b_dis[i] <= m) {
long ispe = pref[a_dis[i] + b_dis[i] + c_dis[i]] + pref[b_dis[i]];
ans = min(ans, ispe);
}
//pl("i : "+i+" sum : "+sum+" b_dis : "+b_dis[i]+" ispe : "+ispe);
}
pl(ans);
}
pw.flush();
pw.close();
}
static int[] BFS(int x) {
LinkedList<Integer> queue = new LinkedList<>();
int dis[] = new int[n+1];
Arrays.fill(dis, -1);
dis[x] = 0;
queue.add(x);
while(!queue.isEmpty()) {
int curr = queue.poll();
for(int e : adj[curr]) {
if(dis[e]==-1) {
dis[e] = 1+dis[curr];
queue.add(e);
}
}
}
return dis;
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
static class FastReader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[1000000];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
} | Java | ["2\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 | 0befe6702492ea637039b08545c17893 | train_000.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 static java.lang.Math.*;
public class Contest {
public static class pair implements Comparable<pair> {
int u;
long val;
public pair(int a, long value) {
u = a;
val = value;
}
@Override
public int compareTo(pair p) {
return Long.compare(val, p.val);
}
}
static int n, m;
static ArrayList<Integer>[] adj;
static int dist[];
static int parent[];
static long inf = (long) 1e16;
static int INF = (int) 1e9;
public static int[] bfs(int s) {
dist = new int[n];
Arrays.fill(dist, -1);
dist[s] = 0;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while (!q.isEmpty()) {
int u = q.poll();
for (int v : adj[u])
if (dist[v] == -1) {
dist[v] = dist[u] + 1;
q.add(v);
}
}
return dist;
}
public static long calc(long[]acc,int single,int Dbl){
if(single+Dbl>m)return inf;
return acc[Dbl]+ acc[single+Dbl];
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
n = sc.nextInt();
m = sc.nextInt();
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
int c = sc.nextInt()-1;
Integer[] p = new Integer[m];
for (int i = 0; i < m; i++) p[i] = sc.nextInt();
adj=new ArrayList[n];
for(int i=0;i<n;i++)adj[i]=new ArrayList<>();
for (int i = 0; i < m; i++)
{
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
adj[u].add(v);
adj[v].add(u);
}
Arrays.sort(p);
int []distA=bfs(a);
int []distB=bfs(b);
int []distC=bfs(c);
long []Acc=new long[m+1];
for(int i=0;i<m;i++)
Acc[i+1]=Acc[i]+p[i];
long ans=inf;
for(int i=0;i<n;i++)
{
ans=min(ans,calc(Acc, distA[i]+distC[i],distB[i]));
}
pw.println(ans);
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public 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, IOException {
return br.ready();
}
}
}
| 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 | a57fd684d43bd073d5927de50933de8e | train_000.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.text.*;
import java.math.*;
import java.awt.Point;
//ArrayList<Integer> ar=new ArrayList<Integer>();
//HashMap<Integer,Integer> h=new HashMap<Integer, Integer>();
//for(i=0;i<n;i++) a[i]=ni();
//int b[]=new int[m];
//int a[]=new int[n];
//int min=Integer.MAX_VALUE;
//int max=Integer.MAX_VALUE;
public class MEXUM{
//SOLUTION BEGIN
// int n;
static ArrayList<ArrayList<Integer>> g;
long MOD = 998244353;
void pre() throws Exception{}
void solve(int TC) throws Exception{
int i;
int n=ni();
int m=ni();
int a=ni()-1;
int b=ni()-1;
int c=ni()-1;
int p[]=new int[m];
for(i=0;i<m;i++) p[i]=ni();
// ArrayList<Integer> g=new ArrayList<>();
g=new ArrayList<ArrayList<Integer>>();
for(i=0;i<n;i++) g.add(new ArrayList<Integer>());
for(i=0;i<m;i++){
int u=ni()-1;
int v=ni()-1;
g.get(u).add(v);
g.get(v).add(u);
}
Arrays.sort(p);
long pr[]=new long [m+1];
for(i=0;i<m;i++){
pr[i+1]=p[i]+pr[i];
}
int da[]=new int[n+1];
int db[]=new int[n+1];
int dc[]=new int[n+1];
bfs(da,a);
bfs(db,b);
bfs(dc,c);
//int ans=Integer.MAX_VALUE;
long ans=Long.MAX_VALUE;
for(i=0;i<n;i++){
if(da[i]+db[i]+dc[i] > m) continue;
ans=Math.min(ans,pr[db[i]]+pr[da[i]+db[i]+dc[i]]);
}
pn(ans);
}
void bfs(int d[],int src){
boolean vis[]=new boolean[d.length ];
vis[src]=true;
Queue<Integer> q=new LinkedList<>();
q.offer(src);
while(!q.isEmpty()){
int cur=q.poll();
// ArrayList<Integer> ar=g.get(cur);
for(int v: g.get(cur)){
if(vis[v]==true) continue;
d[v]=d[cur]+1;
vis[v]=true;
q.offer(v);
}
}
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
DecimalFormat df = new DecimalFormat("0.00000000000");
static boolean multipleTC = true;
FastReader in;PrintWriter out;
void run() throws Exception{
in = new FastReader();
out = new PrintWriter(System.out);
//Solution Credits: Taranpreet Singh
int T = (multipleTC)?ni():1;
pre();for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
new MEXUM().run();
}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str = "";
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
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 | 59a907ca3cd9584eb0aea7e8cab7a0dc | train_000.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.*;
// :)
public class E implements Runnable {
static int inf = Integer.MAX_VALUE;
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n,m,a,b,c,p[];
n=m=a=b=c=0;
int t=sc.nextInt();
while(t--!=0)
{
n=sc.nextInt();
m=sc.nextInt();
a=sc.nextInt()-1;
b=sc.nextInt()-1;
c=sc.nextInt()-1;
p=new int[m];
sa(p,sc);
long pref[] = new long[m];
pref[0]=p[0];
for(int i=1;i<m;i++)
pref[i]+=pref[i-1]+p[i];
ArrayList<ArrayList<Integer>> g = new ArrayList<>();
for(int i=0;i<n;i++)g.add(new ArrayList<>());
for(int i=0;i<m;i++)
{
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
g.get(u).add(v);g.get(v).add(u);
}
int[] disA,disB,disC;
disA=new int[n];
disB=new int[n];
disC=new int[n];
Arrays.fill(disA,inf);
Arrays.fill(disB,inf);
Arrays.fill(disC,inf);
bfs(a,disA,g);
bfs(b,disB,g);
bfs(c,disC,g);
long ans = Long.MAX_VALUE;
for(int i=0;i<n;i++)
{
if(disA[i]+disB[i]+disC[i]>m) continue;
ans = Math.min(ans,(disB[i]==0?0:pref[disB[i]-1])+(disA[i]+disB[i]+disC[i]==0?0:pref[disA[i]+disB[i]+disC[i]-1]));
}
out.println(ans);
}
out.close();
}
static void bfs(int x,int d[],ArrayList<ArrayList<Integer>> g)
{
d[x]=0;
Queue<Integer> q = new LinkedList<>();
q.add(x);
while(q.size()>0)
{
int par = q.remove();
for(int i:g.get(par))
{
if(d[i]==inf)
{
d[i]=d[par]+1;
q.add(i);
}
}
}
}
//========================================================
static class Pair
{
int a,b;
Pair(int aa,int bb)
{
a=aa;
b=bb;
}
}
static void sa(int a[],InputReader sc)
{
for(int i=0;i<a.length;i++)a[i]=sc.nextInt();
Arrays.sort(a);
}
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 E(),"Main",1<<27).start();
}
}
| 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 | 817c8ea1950b1cff136fab8d94519808 | train_000.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.io.PrintWriter;
import java.util.*;
public class B {
static BufferedReader br;
static PrintWriter pw;
static int inf = (int) 1e9;
static long mod = (long) 1e9 + 7;
public static void main(String[] args) throws NumberFormatException, IOException, InterruptedException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int a = Integer.parseInt(st.nextToken()) - 1;
int b = Integer.parseInt(st.nextToken()) - 1;
int c = Integer.parseInt(st.nextToken()) - 1;
int[] p = nxtarr();
g = new ArrayList[n];
for (int i = 0; i < g.length; i++) {
g[i]=new ArrayList<>();
}
for (int i = 0; i < m; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken()) - 1;
int v = Integer.parseInt(st.nextToken()) - 1;
g[u].add(v);
g[v].add(u);
}
Arrays.sort(p);
int[] da = new int[n];
int[] db = new int[n];
int[] dc = new int[n];
Arrays.fill(da, inf);
Arrays.fill(db, inf);
Arrays.fill(dc, inf);
visited = new boolean[n];
bfs(a, da);
bfs(b, db);
bfs(c, dc);
Arrays.sort(p);
long[] prefix = new long[m+1];
for (int i = 1; i < prefix.length; i++) {
prefix[i] = prefix[i - 1] + p[i-1];
}
long min = (long) 1e18;
for (int i = 0; i < n; i++) {
if (da[i] + db[i] + dc[i] > m)
continue;
min = Math.min(min, prefix[db[i]]+prefix[da[i] + db[i] + dc[i]]);
}
pw.println(min);
}
pw.flush();
}
static int n;
static boolean[] visited;
static ArrayList<Integer>[] g;
static void bfs(int s, int[] arr) {
Queue<Integer> q = new LinkedList<Integer>();
q.add(s);
visited = new boolean[n];
visited[s] = true;
arr[s] = 0;
while (!q.isEmpty()) {
int u = q.remove();
for (int v : g[u])
if (!visited[v]) {
visited[v] = true;
q.add(v);
arr[v] = arr[u] + 1;
}
}
}
static class Edge implements Comparable<Edge> {
int node, cost, con;
Edge(int a, int b, int c) {
node = a;
cost = b;
con = c;
}
public int compareTo(Edge e) {
return cost - e.cost;
}
}
static class pair implements Comparable<pair> {
int x;
int y;
public pair(int d, int u) {
x = d;
y = u;
}
public int compareTo(pair o) {
return y - o.y;
}
}
static class triple implements Comparable<triple> {
int x;
int y;
int z;
public triple(int a, int b, int c) {
x = a;
y = b;
z = c;
}
public int compareTo(triple o) {
return x - o.x;
}
}
static int[] nxtarr() throws IOException {
StringTokenizer st = new StringTokenizer(br.readLine());
int[] a = new int[st.countTokens()];
for (int i = 0; i < a.length; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
return a;
}
static long pow(long a, long e) // O(log e)
{
long res = 1;
while (e > 0) {
if ((e & 1) == 1)
res *= a;
a *= a;
e >>= 1;
}
return res;
}
static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
}
| 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 | df4d6e25bcec4b66072dbc9499f0df7e | train_000.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 | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{ static ArrayList<Integer>[] adj;
static int[] da;
static int[] db;
static int[] dc;
public static void main (String[] args) throws java.lang.Exception
{Scanner sc=new Scanner(System.in);
int tc=sc.nextInt();
for(int i=0;i<tc;i++){
int v=sc.nextInt();
int e=sc.nextInt();
int a=sc.nextInt()-1;
int b=sc.nextInt()-1;
int c=sc.nextInt()-1;
da=new int[v];
db=new int[v];
dc=new int[v];
int arr[]=new int[e];
for(int j=0;j<e;j++)
arr[j]=sc.nextInt();
Arrays.sort(arr);
long pre[]=new long[e+1];
for(int j=1;j<=e;j++) {
pre[j]=arr[j-1]+pre[j-1];
}
adj=new ArrayList[v];
for(int k=0;k<v;k++)
adj[k]=new ArrayList<Integer>();
for(int j=0;j<e;j++){
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
adj[x].add(y);
adj[y].add(x);
}
bfs(a,da);
bfs(b,db);
bfs(c,dc);
long ans=pre[e]+pre[e];
for(int j=0;j<v;j++) {
if(da[j]+db[j]+dc[j]<=e) {
ans=Math.min(ans, pre[db[j]]+pre[da[j]+db[j]+dc[j]]);
}
}
System.out.println(ans);
}
// your code goes here
}
static void bfs(int x, int[] d) {
LinkedList<Integer> q=new LinkedList<Integer>();
q.add(x);
while(!q.isEmpty()) {
int cur=q.poll();
for(int i:adj[cur]) {
if(i!=x&&d[i]==0) {
d[i]=d[cur]+1;
q.add(i);
}
}
}
}
}
| 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 | a5da1be32b2ea974432475c286672f21 | train_000.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 int n, m, a, b, c;
static Integer[] ws;
static long[] pre;
static ArrayDeque<Integer>[] edges;
static int[] da, db, dc;
public static void main(String[] args) {
FS sc = new FS();
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
for(int tt = 1; tt <= t; ++tt) {
n = sc.nextInt();
m = sc.nextInt();
a = sc.nextInt() - 1;
b = sc.nextInt() - 1;
c = sc.nextInt() - 1;
ws = new Integer[m];
for(int i = 0; i < m; ++i) ws[i] = sc.nextInt();
Arrays.sort(ws);
edges = new ArrayDeque[n];
for(int i = 0; i < n; ++i) edges[i] = new ArrayDeque<>();
for(int i = 0; i < m; ++i) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
edges[u].add(v);
edges[v].add(u);
}
// do prefix sums for weights
pre = new long[m];
pre[0] = ws[0];
for(int i = 1; i < m; ++i) pre[i] = ws[i] + pre[i - 1];
// get dists
da = new int[n];
db = new int[n];
dc = new int[n];
bfs(a, da);
bfs(b, db);
bfs(c, dc);
long out = Long.MAX_VALUE / 8;
// try all meeting points
for(int meet = 0; meet < n; ++meet) {
int x = db[meet];
int y = da[meet];
int z = dc[meet];
int tot = x + y + z;
if(tot > m) continue;
long curr = 0;
if(tot > 0) curr += pre[tot - 1];
if(x > 0) curr += pre[x - 1];
out = Math.min(out, curr);
}
pw.println(out);
}
pw.flush();
}
static void bfs(int start, int[] d) {
Arrays.fill(d, -1);
ArrayDeque<Integer> ad = new ArrayDeque<>();
d[start] = 0;
ad.add(start);
while(!ad.isEmpty()) {
int curr = ad.poll();
for(int next : edges[curr]) {
if(d[next] == -1) {
d[next] = d[curr] + 1;
ad.add(next);
}
}
}
}
static class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while(!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch(Exception e) {}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
/*
1
2 1 1 1 1
5
1 2
1
2 1 1 1 2
5
1 2
*/ | 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 | b496daffb3e314178a9aac146ef0967c | train_000.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
{
static class Graph
{
HashMap<Integer,ArrayList<Integer>> graph;
int n;
public Graph(int n)
{
this.n=n;
graph=new HashMap<>();
for(int i=1;i<=n;i++)
{
graph.put(i,new ArrayList<Integer>());
}
}
public void addEdge(int u,int v)
{
graph.get(u).add(v);
graph.get(v).add(u);
}
public int[] bfs(int source)
{
int arr[]=new int[n+1];
arr[source]=0;
Queue<Integer> queue=new LinkedList<>();
queue.add(source);
boolean visited[]=new boolean[n+1];
visited[source]=true;
while(queue.isEmpty()==false)
{
int temp=queue.remove();
for(int i:graph.get(temp))
{
if(!visited[i])
{
visited[i]=true;
arr[i]=arr[temp]+1;
queue.add(i);
}
}
}
return arr;
}
public void printGraph()
{
for(Map.Entry e:graph.entrySet())
{
System.out.print(e.getKey()+"->");
ArrayList<Integer> arr=(ArrayList)e.getValue();
for(Object o:arr)
{
System.out.print((int)o+",");
}
System.out.println();
}
}
}
public static void main(String[] args)throws IOException {
FastReader kb=new FastReader();
int t=kb.nextInt();
while(t-->0)
{
int n=kb.nextInt(),m=kb.nextInt(),a=kb.nextInt(),b=kb.nextInt(),c=kb.nextInt();
Graph g=new Graph(n);
long arr[]=new long[m+1];
for(int i=1;i<=m;i++)arr[i]=kb.nextLong();
Arrays.sort(arr);
arr[0]=0;
for(int i=1;i<=m;i++)arr[i]=arr[i]+arr[i-1];
for(int i=0;i<m;i++)
{
int u=kb.nextInt(),v=kb.nextInt();
g.addEdge(u,v);
}
int ad[]=g.bfs(a);
int bd[]=g.bfs(b);
int cd[]=g.bfs(c);
long ans=Long.MAX_VALUE;
for(int i=1;i<=n;i++)
{
int temp=ad[i]+bd[i]+cd[i];
int extra=bd[i];
if((temp)>m)continue;
long curr=arr[extra]+arr[temp];
ans=Math.min(ans,curr);
}
System.out.println(ans);
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["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 | 499b74c59ee734f444e5aeef6d8bf0d0 | train_000.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 implements Runnable {
boolean judge = false;
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int t = scn.nextInt();
while (t-- > 0) {
int n = scn.nextInt(), m = scn.nextInt(), a = scn.nextInt() - 1, b = scn.nextInt() - 1,
c = scn.nextInt() - 1;
int[] price = new int[m];
for (int i = 0; i < m; i++)
price[i] = scn.nextInt();
price = scn.shuffle(price);
Arrays.sort(price);
long[] pre = new long[m + 1];
for (int i = 1; i <= m; i++)
pre[i] = pre[i - 1] + (long) price[i - 1];
int[] from = new int[m], to = new int[m];
for (int i = 0; i < m; i++) {
from[i] = scn.nextInt() - 1;
to[i] = scn.nextInt() - 1;
}
int[][] g = packU(n, from, to);
int[] one = bfs(g, a), two = bfs(g, b), three = bfs(g, c);
long res = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
int x = one[i], y = two[i], k = three[i];
if (x + y + k > m)
continue;
long dist = pre[y] + pre[x + y + k];
res = Math.min(res, dist);
}
out.println(res);
}
out.close();
}
int[] bfs(int[][] g, int sv) {
int[] level = new int[g.length];
Arrays.fill(level, -1);
Queue<Integer> q = new LinkedList<>();
q.add(sv);
int lvl = 0;
level[sv] = 0;
while (!q.isEmpty()) {
int size = q.size();
while (size-- > 0) {
Integer temp = q.poll();
for (int child : g[temp]) {
if (level[child] == -1) {
q.add(child);
level[child] = lvl + 1;
}
}
}
lvl++;
}
return level;
}
static int[][] packU(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to)
p[t]++;
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null || judge;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new A(), "Main", 1 << 28).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
}
} | 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 | 1f923a2a4f98f528406f55528fc04f7b | train_000.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 | //package main;
import java.io.*;
import java.util.*;
public final class Main {
BufferedReader br;
StringTokenizer stk;
public static void main(String[] args) throws Exception {
new Main().run();
}
{
stk = null;
br = new BufferedReader(new InputStreamReader(System.in));
}
long mod = 998244353;
StringBuilder res = new StringBuilder(100005);
void run() throws Exception {
int t = ni();
while(t-- > 0) {
int n = ni();
int m = ni();
int a = ni();
int b = ni();
int c = ni();
long[] p = new long[m];
for(int i = 0; i < m; i++) {
p[i] = nl();
}
shuffle(p);
Arrays.sort(p);
for(int i = 1; i < m; i++) {
p[i] += p[i - 1];
}
Node[] graph = new Node[n + 1];
for(int i = 1; i <= n; i++) {
graph[i] = new Node();
}
for(int i = 0; i < m; i++) {
int u = ni();
int v = ni();
graph[u].adj.add(v);
graph[v].adj.add(u);
}
int[] spa = new int[n + 1];
int[] spb = new int[n + 1];
int[] spc = new int[n + 1];
Arrays.fill(spa, Integer.MAX_VALUE / 2);
Arrays.fill(spb, Integer.MAX_VALUE / 2);
Arrays.fill(spc, Integer.MAX_VALUE / 2);
spa[a] = spb[b] = spc[c] = 0;
bfs(a, graph, spa);
bfs(b, graph, spb);
bfs(c, graph, spc);
long total = Long.MAX_VALUE / 5;
for(int i = 1; i <= n; i++) {
int x = i;
int ax = spa[x];
int bx = spb[x];
int cx = spc[x];
//System.out.println(ax + " " + bx + " " + cx);
if(ax + bx + cx > m) {
continue;
}
int temp = ax;
ax = bx;
bx = temp;
long cost = 0;
int used = 0;
cost += 2L * get(0, ax - 1, p);
used = ax;
cost += get(used, ax + bx - 1, p);
used = ax + bx;
cost += get(used, ax + bx + cx - 1, p);
total = Math.min(total, cost);
}
res.append(total).append("\n");
}
System.out.print(res);
}
void bfs(int src, Node[] graph, int[] sp) {
Queue<Integer> queue = new LinkedList<>();
queue.add(src);
while(!queue.isEmpty()) {
int cur = queue.remove();
for(int adj : graph[cur].adj) {
if(sp[adj] > sp[cur] + 1) {
sp[adj] = sp[cur] + 1;
queue.add(adj);
}
}
}
}
class Node {
HashSet<Integer> adj;
public Node() {
adj = new HashSet<>();
}
}
//Reader & Writer
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens())
stk = new StringTokenizer(br.readLine(), " ");
return stk.nextToken();
}
String nt() throws Exception {
return nextToken();
}
int ni() throws Exception {
return Integer.parseInt(nextToken());
}
long nl() throws Exception {
return Long.parseLong(nextToken());
}
double nd() throws Exception {
return Double.parseDouble(nextToken());
}
//Some Misc methods
long get(int l, int r, long[] a) {
if(r < l) return 0;
return l == 0 ? a[r] : a[r] - a[l - 1];
}
void shuffle(long[] a) {
Random r = new Random();
for(int i = 0; i < a.length; i++) {
int idx = r.nextInt(a.length);
long temp = a[i];
a[i] = a[idx];
a[idx] = temp;
}
}
} | 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 | 5454493c9509597738cfb0a2d2be0caa | train_000.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 | //package main;
import java.io.*;
import java.util.*;
public final class Main {
BufferedReader br;
StringTokenizer stk;
public static void main(String[] args) throws Exception {
new Main().run();
}
{
stk = null;
br = new BufferedReader(new InputStreamReader(System.in));
}
long mod = 998244353;
StringBuilder res = new StringBuilder(100005);
void run() throws Exception {
int t = ni();
while(t-- > 0) {
int n = ni();
int m = ni();
int a = ni();
int b = ni();
int c = ni();
long[] p = new long[m];
for(int i = 0; i < m; i++) {
p[i] = nl();
}
shuffle(p);
Arrays.sort(p);
for(int i = 1; i < m; i++) {
p[i] += p[i - 1];
}
Node[] graph = new Node[n + 1];
for(int i = 1; i <= n; i++) {
graph[i] = new Node();
}
for(int i = 0; i < m; i++) {
int u = ni();
int v = ni();
graph[u].adj.add(v);
graph[v].adj.add(u);
}
int[] spa = new int[n + 1];
int[] spb = new int[n + 1];
int[] spc = new int[n + 1];
Arrays.fill(spa, Integer.MAX_VALUE / 2);
Arrays.fill(spb, Integer.MAX_VALUE / 2);
Arrays.fill(spc, Integer.MAX_VALUE / 2);
spa[a] = spb[b] = spc[c] = 0;
bfs(a, graph, spa);
bfs(b, graph, spb);
bfs(c, graph, spc);
long total = Long.MAX_VALUE / 5;
for(int i = 1; i <= n; i++) {
int x = i;
int ax = spa[x];
int bx = spb[x];
int cx = spc[x];
//System.out.println(ax + " " + bx + " " + cx);
if(ax + bx + cx > m) {
continue;
}
int temp = ax;
ax = bx;
bx = temp;
long cost = 0;
cost += 2L * get(0, ax - 1, p);
cost += get(ax, ax + bx - 1, p);
cost += get(ax + bx, ax + bx + cx - 1, p);
total = Math.min(total, cost);
}
res.append(total).append("\n");
}
System.out.print(res);
}
void bfs(int src, Node[] graph, int[] sp) {
Queue<Integer> queue = new LinkedList<>();
queue.add(src);
while(!queue.isEmpty()) {
int cur = queue.remove();
for(int adj : graph[cur].adj) {
if(sp[adj] > sp[cur] + 1) {
sp[adj] = sp[cur] + 1;
queue.add(adj);
}
}
}
}
class Node {
HashSet<Integer> adj;
public Node() {
adj = new HashSet<>();
}
}
//Reader & Writer
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens())
stk = new StringTokenizer(br.readLine(), " ");
return stk.nextToken();
}
String nt() throws Exception {
return nextToken();
}
int ni() throws Exception {
return Integer.parseInt(nextToken());
}
long nl() throws Exception {
return Long.parseLong(nextToken());
}
double nd() throws Exception {
return Double.parseDouble(nextToken());
}
//Some Misc methods
long get(int l, int r, long[] a) {
if(r < l) return 0;
return l == 0 ? a[r] : a[r] - a[l - 1];
}
void shuffle(long[] a) {
Random r = new Random();
for(int i = 0; i < a.length; i++) {
int idx = r.nextInt(a.length);
long temp = a[i];
a[i] = a[idx];
a[idx] = temp;
}
}
} | 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 | 0cc354fdf97f5929a7c40bbc110d61a1 | train_000.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.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class E {
static int oo=(int)1e8;
public static void main(String[] args) {
FastScanner fs=new FastScanner();
int T=fs.nextInt();
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt(), m=fs.nextInt(), a=fs.nextInt()-1, b=fs.nextInt()-1, c=fs.nextInt()-1;
Node[] nodes=new Node[n];
for (int i=0; i<n; i++) nodes[i]=new Node();
int[] prices=fs.readArray(m);
sort(prices);
long[] cs=new long[m+1];
for (int i=1; i<=m; i++) cs[i]=cs[i-1]+prices[i-1];
for (int i=0; i<m; i++) {
int aa=fs.nextInt()-1, bb=fs.nextInt()-1;
nodes[aa].adj.add(nodes[bb]);
nodes[bb].adj.add(nodes[aa]);
}
bfs(nodes[a], nodes);
for (int i=0; i<n; i++) nodes[i].aDist=nodes[i].dist;
bfs(nodes[b], nodes);
for (int i=0; i<n; i++) nodes[i].bDist=nodes[i].dist;
bfs(nodes[c], nodes);
for (int i=0; i<n; i++) nodes[i].cDist=nodes[i].dist;
long ans=Long.MAX_VALUE;
for (Node nn:nodes) {
int bCost=nn.bDist;
int otherCost=nn.aDist+nn.cDist;
if (bCost+otherCost>m) continue;
long totalCost=cs[otherCost+bCost];
totalCost+=cs[bCost];
ans=Math.min(ans, totalCost);
}
System.out.println(ans);
}
}
static void bfs(Node from, Node[] nodes) {
ArrayDeque<Node> bfs=new ArrayDeque<>();
for (Node nn:nodes) nn.dist=oo;
bfs.add(from);
from.dist=0;
while(!bfs.isEmpty()) {
Node next=bfs.remove();
for (Node nn:next.adj) {
if (nn.dist==oo) {
nn.dist=next.dist+1;
bfs.add(nn);
}
}
}
}
static class Node {
ArrayList<Node> adj=new ArrayList<>();
int dist;
int aDist, bDist, cDist;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (!st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) {
a[i]=nextInt();
}
return a;
}
public 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 | 36e35f2d24ab1fdd1792fceb54757a25 | train_000.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 R635D3E {
public static void main(String[] args) throws Exception{
int num = 998244353;
// TODO Auto-generated method stub
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(bf.readLine());
for(int i = 0;i<t;i++){
StringTokenizer st = new StringTokenizer(bf.readLine());
int 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());
ArrayList<Integer> prices = new ArrayList<Integer>();
StringTokenizer st1 = new StringTokenizer(bf.readLine());
for(int j = 0;j<m;j++){
prices.add(Integer.parseInt(st1.nextToken()));
}
Map<Integer, ArrayList<Integer>> graph = new HashMap<Integer, ArrayList<Integer>>();
for(int j = 0;j<m;j++){
StringTokenizer st2 = new StringTokenizer(bf.readLine());
int v1 = Integer.parseInt(st2.nextToken());
int v2 = Integer.parseInt(st2.nextToken());
if (graph.containsKey(v1))
graph.get(v1).add(v2);
else{
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(v2);
graph.put(v1, temp);
}
if (graph.containsKey(v2))
graph.get(v2).add(v1);
else{
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(v1);
graph.put(v2, temp);
}
}
Set<Integer> atbtc = new HashSet<Integer>();
Map<Integer, Integer> predecessor = new HashMap<Integer, Integer>();
int[][] arraydistancesabc = new int[3][n+1];
arraydistancesabc[0][a] = 0;
Set<Integer> visited = new HashSet<Integer>();
Queue<Integer> bfs = new LinkedList<Integer>();
bfs.add(a);
visited.add(a);
while(!bfs.isEmpty()){
int vertex = bfs.remove();
for (int k: graph.get(vertex)){
if (!visited.contains(k)){
predecessor.put(k, vertex);
bfs.add(k);
visited.add(k);
arraydistancesabc[0][k] = arraydistancesabc[0][vertex] + 1;
}
}
}
int asdf = b;
atbtc.add(asdf);
while (predecessor.containsKey(asdf)){
asdf = predecessor.get(asdf);
atbtc.add(asdf);
}
Map<Integer, Integer> predecessor1 = new HashMap<Integer, Integer>();
arraydistancesabc[1][b] = 0;
visited.clear();
bfs.clear();
bfs.add(b);
visited.add(b);
while(!bfs.isEmpty()){
int vertex = bfs.remove();
for (int k: graph.get(vertex)){
if (!visited.contains(k)){
predecessor1.put(k, vertex);
bfs.add(k);
visited.add(k);
arraydistancesabc[1][k] = arraydistancesabc[1][vertex] + 1;
}
}
}
Set<Integer> atbtc2 = new HashSet<Integer>();
asdf = c;
atbtc2.add(asdf);
while (predecessor1.containsKey(asdf)){
asdf = predecessor1.get(asdf);
atbtc2.add(asdf);
}
atbtc.retainAll(atbtc2);
arraydistancesabc[2][c] = 0;
visited.clear();
bfs.clear();
bfs.add(c);
visited.add(c);
while(!bfs.isEmpty()){
int vertex = bfs.remove();
for (int k: graph.get(vertex)){
if (!visited.contains(k)){
bfs.add(k);
visited.add(k);
arraydistancesabc[2][k] = arraydistancesabc[2][vertex] + 1;
}
}
}
Collections.sort(prices);
ArrayList<Long> prefixprices = new ArrayList<Long>();
long totalsum =0 ;
for(int j = 0;j<prices.size();j++){
prefixprices.add(totalsum);
totalsum+= prices.get(j);
}
prefixprices.add(totalsum);
long minsum = Long.MAX_VALUE;
int minindex = -1;
for (int k = 1;k<=n;k++){
if (arraydistancesabc[0][k] + arraydistancesabc[1][k] +arraydistancesabc[2][k] <=m && prefixprices.get(arraydistancesabc[0][k] + arraydistancesabc[1][k] +arraydistancesabc[2][k])+ prefixprices.get(arraydistancesabc[1][k])< minsum){
minsum = prefixprices.get(arraydistancesabc[0][k] + arraydistancesabc[1][k] +arraydistancesabc[2][k])+ prefixprices.get(arraydistancesabc[1][k]);
minindex = k;
}
}
System.out.println(minsum);
}
}
}
| 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 | acccec0660a6f9760d3991d8480f6cc1 | train_000.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 | /*
ID: tommatt1
LANG: JAVA
TASK:
*/
import java.util.*;
import java.io.*;
public class cf1343e{
static ArrayList<Integer>[] adj;
static int[] da;
static int[] db;
static int[] dc;
public static void main(String[] args)throws IOException {
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//BufferedReader bf=new BufferedReader(new FileReader("cf1343e.in"));
//PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cf1343e.out")));
StringTokenizer st=new StringTokenizer(bf.readLine());
int t=Integer.parseInt(st.nextToken());
for(int tt=0;tt<t;tt++) {
st=new StringTokenizer(bf.readLine());
int n=Integer.parseInt(st.nextToken());
int m=Integer.parseInt(st.nextToken());
int a=Integer.parseInt(st.nextToken())-1;
int b=Integer.parseInt(st.nextToken())-1;
int c=Integer.parseInt(st.nextToken())-1;
adj=new ArrayList[n];
da=new int[n];
db=new int[n];
dc=new int[n];
for(int i=0;i<n;i++) {
adj[i]=new ArrayList<Integer>();
}
int[] px=new int[m];
long[] pp=new long[m+1];
st=new StringTokenizer(bf.readLine());
for(int i=0;i<m;i++) {
px[i]=Integer.parseInt(st.nextToken());
}
Arrays.sort(px);
for(int i=1;i<=m;i++) {
pp[i]=px[i-1]+pp[i-1];
}
for(int i=0;i<m;i++) {
st=new StringTokenizer(bf.readLine());
int a1=Integer.parseInt(st.nextToken())-1;
int a2=Integer.parseInt(st.nextToken())-1;
adj[a1].add(a2);
adj[a2].add(a1);
}
bfs(a,da);
bfs(b, db);
bfs(c, dc);
long ans=pp[m]+pp[m];
for(int i=0;i<n;i++) {
if(da[i]+db[i]+dc[i]<=m) {
ans=Math.min(ans, pp[db[i]]+pp[da[i]+db[i]+dc[i]]);
}
}
out.println(ans);
}
out.close();
}
static void bfs(int x, int[] d) {
LinkedList<Integer> q=new LinkedList<Integer>();
q.add(x);
while(!q.isEmpty()) {
int cur=q.poll();
for(int i:adj[cur]) {
if(i!=x&&d[i]==0) {
d[i]=d[cur]+1;
q.add(i);
}
}
}
}
}
| 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 | b6deb3a5bbe7313b27e1a7f08186e280 | train_000.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 | //make sure to make new file!
import java.io.*;
import java.util.*;
public class E636{
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int t = Integer.parseInt(f.readLine());
for(int q1 = 1; q1 <= t; q1++){
StringTokenizer st = new StringTokenizer(f.readLine());
int 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());
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(n+1);
for(int k = 0; k <= n; k++) adj.add(new ArrayList<Integer>());
Long[] p = new Long[m];
st = new StringTokenizer(f.readLine());
for(int k = 0; k < m; k++){
p[k] = Long.parseLong(st.nextToken());
}
Arrays.sort(p);
long[] psums = new long[m+1];
psums[0] = 0;
for(int k = 1; k <= m; k++){
psums[k] = psums[k-1]+p[k-1];
}
for(int k = 0; k < m; k++){
st = new StringTokenizer(f.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
adj.get(x).add(y);
adj.get(y).add(x);
}
int[] A = new int[n+1];
int[] B = new int[n+1];
int[] C = new int[n+1];
Arrays.fill(A,-1);
Arrays.fill(B,-1);
Arrays.fill(C,-1);
//fill A
Queue<State> q = new LinkedList<State>();
q.add(new State(a,0));
A[a] = 0;
while(!q.isEmpty()){
State s = q.poll();
for(int nei : adj.get(s.v)){
if(A[nei] == -1){
q.add(new State(nei,s.d+1));
A[nei] = s.d+1;
}
}
}
//fill B
q = new LinkedList<State>();
q.add(new State(b,0));
B[b] = 0;
while(!q.isEmpty()){
State s = q.poll();
for(int nei : adj.get(s.v)){
if(B[nei] == -1){
q.add(new State(nei,s.d+1));
B[nei] = s.d+1;
}
}
}
q = new LinkedList<State>();
q.add(new State(c,0));
C[c] = 0;
while(!q.isEmpty()){
State s = q.poll();
for(int nei : adj.get(s.v)){
if(C[nei] == -1){
q.add(new State(nei,s.d+1));
C[nei] = s.d+1;
}
}
}
long answer = Long.MAX_VALUE;
for(int k = 1; k <= n; k++){
if(A[k] + B[k] + C[k] > m) continue;
answer = Math.min(answer,psums[B[k]] + psums[A[k]+B[k]+C[k]]);
}
out.println(answer);
}
out.close();
}
public static class State{
int v;
int d;
public State(int a, int b){
v = a;
d = b;
}
}
} | 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 | 24469de5142e2355e5696346280b0956 | train_000.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 | /**
* Created by Aminul on 4/21/2020.
*/
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class E {
static ArrayDeque<Integer> g[];
public static void main(String[] args) throws Exception {
FastReader in = new FastReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int test = in.nextInt();
for (int t = 1; t <= test; t++) {
int n = in.nextInt(), m = in.nextInt(), a = in.nextInt(), b = in.nextInt(), c = in.nextInt();
int arr[] = new int[m + 1];
g = genDQ(n + 1);
for (int i = 1; i <= m; i++) {
arr[i] = in.nextInt();
}
shuffle(arr);
Arrays.sort(arr);
long sum[] = new long[m + 1];
for (int i = 1; i <= m; i++) {
sum[i] = sum[i - 1] + arr[i];
}
for (int i = 1; i <= m; i++) {
int u = in.nextInt(), v = in.nextInt();
g[u].addLast(v);
g[v].addLast(u);
}
int va[] = bfs(a, n);
int vb[] = bfs(b, n);
int vc[] = bfs(c, n);
long res = (long) 2e18;
for (int i = 1; i <= n; i++) {
int common = vb[i];
int da = va[i], dc = vc[i];
int tot = common + da + dc;
if(tot > m) continue;
long dist = sum[common] + sum[tot];
res = min(res, dist);
}
pw.println(res);
}
pw.close();
}
static int[] bfs(int src, int n) {
int vis[] = new int[n + 1];
Arrays.fill(vis, -1);
Queue<Integer> queue = new ArrayDeque<>();
queue.add(src);
vis[src] = 0;
while (!queue.isEmpty()) {
int p = queue.poll();
for (int v : g[p]) {
if (vis[v] == -1) {
vis[v] = vis[p] + 1;
queue.add(v);
}
}
}
return vis;
}
static <T> ArrayDeque<T>[] genDQ(int n) {
ArrayDeque<T> list[] = new ArrayDeque[n];
for (int i = 0; i < n; i++) list[i] = new ArrayDeque<T>();
return list;
}
public static void shuffle(int[] a) {
Random rnd = new Random();
for (int i = a.length - 1; i >= 1; i--) {
int j = rnd.nextInt(i + 1);
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
static void debug(Object... obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public String nextLine() {
int c = skip();
StringBuilder sb = new StringBuilder();
while (!isEndOfLine(c)) {
sb.appendCodePoint(c);
c = readByte();
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public char readChar() {
return (char) skip();
}
}
} | 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 | c5c66f7757089ffdd27bcefcf283a692 | train_000.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 Sol{
public static List<Integer> adj[];
public static int n,m,a,b,c;
public static long p[];
public static int dist1[];
public static int dist2[];
public static int dist3[];
public static long psum[];
public static void main(String[] args) throws IOException{
FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = sc.nextInt();
test: while(t-->0) {
n = sc.nextInt();
m = sc.nextInt();
a = sc.nextInt()-1;
b = sc.nextInt()-1;
c = sc.nextInt()-1;
p = new long[m];
adj = new ArrayList[n];
for(int i=0; i<n; i++) {
adj[i] = new ArrayList<>();
}
dist1 = new int[n];
dist2 = new int[n];
dist3 = new int[n];
Arrays.fill(dist1, -1);
Arrays.fill(dist2, -1);
Arrays.fill(dist3, -1);
psum = new long[m+1];
for(int i=0; i<m; i++) {
p[i] = sc.nextLong();
}
shuffle(p);
Arrays.sort(p);
psum[0] = 0;
for(int i=0; i<m; i++) {
psum[i+1] = psum[i]+p[i];
}
for(int i=0; i<m; i++) {
int e = sc.nextInt()-1;
int f = sc.nextInt()-1;
adj[e].add(f);
adj[f].add(e);
}
dist1[a] = 0;
dist2[b] = 0;
dist3[c] = 0;
BFS1(a);
BFS2(b);
BFS3(c);
long min = Long.MAX_VALUE;
for(int i=0; i<n; i++) {
if(dist1[i] + dist2[i] + dist3[i]>m) continue;
long curr = psum[dist1[i]+dist2[i]+dist3[i]];
curr+=psum[dist2[i]];
min = Math.min(min, curr);
}
System.out.println(min);
}
}
public static void BFS1(int src) {
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(src);
while(!q.isEmpty()) {
int curr = q.poll();
for(int i:adj[curr]) {
if(dist1[i]!=-1) continue;
dist1[i] = dist1[curr] +1;
q.addLast(i);
}
}
}
public static void BFS2(int src) {
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(src);
while(!q.isEmpty()) {
int curr = q.poll();
for(int i:adj[curr]) {
if(dist2[i]!=-1) continue;
dist2[i] = dist2[curr] +1;
q.addLast(i);
}
}
}
public static void BFS3(int src) {
ArrayDeque<Integer> q = new ArrayDeque<>();
q.add(src);
while(!q.isEmpty()) {
int curr = q.poll();
for(int i:adj[curr]) {
if(dist3[i]!=-1) continue;
dist3[i] = dist3[curr] +1;
q.addLast(i);
}
}
}
public 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;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
st = null;
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| 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 | 5410bf5367cce1d5831dd5e24fb47f52 | train_000.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 Task {
static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
static void bfs(List<Integer>[] map,long[] p,int[][] d,int s,int i){
boolean[] b=new boolean[d[0].length];
Queue<Integer> q=new LinkedList<>();
q.add(s); b[s]=true;
while(!q.isEmpty()){
int curr=q.poll();
for(int k:map[curr]){
if(!b[k]){
b[k]=true;
d[i][k]=d[i][curr]+1;
q.add(k);
}
}
}
}
public static void main(String args[]) throws IOException {
assign();
int t=int_v(read());
while(t--!=0){
int[] n1=int_arr();
int n=n1[0],m=n1[1],a=n1[2],b=n1[3],c=n1[4];
int[][] d=new int[3][n+1];
long[] p=long_arr();
List<Integer>[] map=new ArrayList[n+1];
for(int i=1;i<=n;i++){map[i]=new ArrayList<>();}
for(int i=0;i<m;i++){
int[] xx=int_arr();
map[xx[0]].add(xx[1]);
map[xx[1]].add(xx[0]);
}
Arrays.sort(p);
for(int i=1;i<m;i++){p[i]+=p[i-1];}
bfs(map,p,d,a,0);
bfs(map,p,d,b,1);
bfs(map,p,d,c,2);
long res=(long)1e17;
for(int i=1;i<=n;i++){
int x=d[0][i],y=d[1][i],z=d[2][i];
if((y-1)>=m||(x+y+z-1)>=m){continue;}
long tmp=y-1<0?0:p[y-1];
tmp+=x+y+z-1<0?0:p[x+y+z-1];
res=Math.min(res,tmp);
}
out.write(res+"\n");
}
out.flush();
}
}
| 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 | ee02618dda13935c48f64d7ca5fb8d4a | train_000.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 Task {
static BufferedReader s1;
static BufferedWriter out;
static String read() throws IOException{String line="";while(line.length()==0){line=s1.readLine();continue;}return line;}
static int int_v (String s1){return Integer.parseInt(s1);}
static long long_v(String s1){return Long.parseLong(s1);}
static int[] int_arr() throws IOException{String[] a=read().split(" ");int[] b=new int[a.length];for(int i=0;i<a.length;i++){b[i]=int_v(a[i]);}return b;}
static long[] long_arr() throws IOException{String[] a=read().split(" ");long[] b=new long[a.length];for(int i=0;i<a.length;i++){b[i]=long_v(a[i]);}return b;}
static void assign(){s1=new BufferedReader(new InputStreamReader(System.in));out=new BufferedWriter(new OutputStreamWriter(System.out));}
static void bfs(Map<Integer,Set<Integer>> map,long[] p,int[][] d,int s,int i){
boolean[] b=new boolean[d[0].length];
Queue<Integer> q=new LinkedList<>();
q.add(s); b[s]=true;
while(!q.isEmpty()){
int curr=q.poll();
if(map.get(curr)==null){continue;}
for(int k:map.get(curr)){
if(!b[k]){
b[k]=true;
d[i][k]=d[i][curr]+1;
q.add(k);
}
}
}
}
public static void main(String args[]) throws IOException {
assign();
int t=int_v(read());
while(t--!=0){
int[] n1=int_arr();
int n=n1[0],m=n1[1],a=n1[2],b=n1[3],c=n1[4];
int[][] d=new int[3][n+1];
long[] p=long_arr();
Map<Integer,Set<Integer>> map=new HashMap<>();
for(int i=0;i<m;i++){
int[] xx=int_arr();
map.computeIfAbsent(xx[0],k->new HashSet<Integer>()).add(xx[1]);
map.computeIfAbsent(xx[1],k->new HashSet<Integer>()).add(xx[0]);
}
Arrays.sort(p);
for(int i=1;i<m;i++){p[i]+=p[i-1];}
bfs(map,p,d,a,0);
bfs(map,p,d,b,1);
bfs(map,p,d,c,2);
long res=(long)1e17;
for(int i=1;i<=n;i++){
int x=d[0][i],y=d[1][i],z=d[2][i];
if((y-1)>=m||(x+y+z-1)>=m){continue;}
long tmp=y-1<0?0:p[y-1];
tmp+=x+y+z-1<0?0:p[x+y+z-1];
res=Math.min(res,tmp);
}
out.write(res+"\n");
}
out.flush();
}
}
| 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 | 191430198bd368eba441229cc1e65f65 | train_000.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 Solution {
private static BufferedReader br;
private static StreamTokenizer st;
private static PrintWriter pw;
static final int INF = 1000000007;
static final int MOD = 998244353;
static List<Integer> edges[];
static void bfs(int r, int dst[]) {
Queue<Integer> queue = new LinkedList<>();
boolean vis[] = new boolean[dst.length];
vis[r] = true;
dst[r] = 0;
queue.offer(r);
while (!queue.isEmpty()) {
int x = queue.size();
while (x-- > 0) {
int f = queue.poll();
List<Integer> es = edges[f];
for (int i = 0; i < es.size(); i++) {
int t = es.get(i);
if (vis[t]) {
continue;
}
vis[t] = true;
dst[t] = dst[f] + 1;
queue.offer(t);
}
}
}
}
private static void solve() throws IOException {
int tt = nextInt();
for (int cs = 1; cs <= tt; cs++) {
int n = nextInt();
int m = nextInt();
int a = nextInt();
int b = nextInt();
int c = nextInt();
long p[] = new long[m + 1];
for (int i = 1; i <= m; i++) {
p[i] = nextInt();
}
Arrays.sort(p);
for (int i = 1; i <= m; i++) {
p[i] += p[i - 1];
}
edges = new List[n + 1];
for (int i = 1; i <= n; i++) {
edges[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int f = nextInt();
int t = nextInt();
edges[f].add(t);
edges[t].add(f);
}
int da[] = new int[n + 1];
int db[] = new int[n + 1];
int dc[] = new int[n + 1];
bfs(a, da);
bfs(b, db);
bfs(c, dc);
long res = Long.MAX_VALUE;
for (int i = 1; i <= n; i++) {
int x = da[i];
int y = db[i];
int z = dc[i];
if (x + y + z <= m) {
res = Math.min(res, p[y] + p[x + y + z]);
}
}
pw.print(res);
// pw.format("Case #%d: %f", cs, 1.0 - del);
if (cs < tt) {
pw.println();
}
}
}
static void getDiv(Map<Integer, Integer> map, int n) {
int sqrt = (int) Math.sqrt(n);
for (int i = sqrt; i >= 2; i--) {
if (n % i == 0) {
getDiv(map, i);
getDiv(map, n / i);
return;
}
}
map.put(n, map.getOrDefault(n, 0) + 1);
}
public static boolean[] generatePrime(int n) {
boolean p[] = new boolean[n + 1];
p[2] = true;
for (int i = 3; i <= n; i += 2) {
p[i] = true;
}
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (!p[i]) {
continue;
}
for (int j = i * i; j <= n; j += i << 1) {
p[j] = false;
}
}
return p;
}
static boolean isPrime(long n) { //determines if n is a prime number
int p[] = {2, 3, 5, 233, 331};
int pn = p.length;
long s = 0, t = n - 1;//n - 1 = 2^s * t
while ((t & 1) == 0) {
t >>= 1;
++s;
}
for (int i = 0; i < pn; ++i) {
if (n == p[i]) {
return true;
}
long pt = pow(p[i], t, n);
for (int j = 0; j < s; ++j) {
long cur = llMod(pt, pt, n);
if (cur == 1 && pt != 1 && pt != n - 1) {
return false;
}
pt = cur;
}
if (pt != 1) {
return false;
}
}
return true;
}
static long llMod(long a, long b, long mod) {
return (a * b - (long) ((double) a / mod * b + 0.5) * mod + mod) % mod;
// long r = 0;
// a %= mod;
// b %= mod;
// while (b > 0) {
// if ((b & 1) == 1) {
// r = (r + a) % mod;
// }
// b >>= 1;
// a = (a << 1) % mod;
// }
// return r;
}
static int pow(long a, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = (ans * a) % MOD;
}
a = (a * a) % MOD;
n >>= 1;
}
return (int) ans;
}
static int pow(long a, long n, long mod) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans = llMod(ans, a, mod);
}
a = llMod(a, a, mod);
n >>= 1;
}
return (int) ans;
}
private static long[][] initC(int n) {
long c[][] = new long[n][n];
for (int i = 0; i < n; i++) {
c[i][0] = 1;
}
for (int i = 1; i < n; i++) {
for (int j = 1; j <= i; j++) {
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
}
}
return c;
}
/**
* ps: n >= m, choose m from n;
*/
private static int c(long n, long m) {
if (m > n) {
n ^= m;
m ^= n;
n ^= m;
}
m = Math.min(m, n - m);
long top = 1;
long bot = 1;
for (long i = n - m + 1; i <= n; i++) {
top = (top * i) % MOD;
}
for (int i = 1; i <= m; i++) {
bot = (bot * i) % MOD;
}
return (int) ((top * pow(bot, MOD - 2)) % MOD);
}
static int gcd(int a, int b) {
if (a < b) {
a ^= b;
b ^= a;
a ^= b;
}
while (b != 0) {
int tmp = a % b;
a = b;
b = tmp;
}
return a;
}
static boolean even(long n) {
return (n & 1) == 0;
}
public static void main(String args[]) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StreamTokenizer(br);
pw = new PrintWriter(new OutputStreamWriter(System.out));
st.ordinaryChar('\'');
st.ordinaryChar('\"');
st.ordinaryChar('/');
long t = System.currentTimeMillis();
solve();
pw.flush();
}
private static long[] anLong(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
private static String next(int len) throws IOException {
char ch[] = new char[len];
int cur = 0;
char c;
while ((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t') ;
do {
ch[cur++] = c;
} while (!((c = (char) br.read()) == '\n' || c == '\r' || c == ' ' || c == '\t'));
return String.valueOf(ch, 0, cur);
}
private static int nextInt() throws IOException {
st.nextToken();
return (int) st.nval;
}
private static long nextLong() throws IOException {
st.nextToken();
return (long) st.nval;
// return Long.parseLong(nextLine());
}
private static double nextDouble() throws IOException {
st.nextToken();
return st.nval;
}
private static String[] nextSS(String reg) throws IOException {
return br.readLine().split(reg);
}
private static String nextLine() throws IOException {
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 | cd55ceb07c7422af74f88c6e0bfebea4 | train_000.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.*;
import javax.rmi.ssl.SslRMIClientSocketFactory;
public class tr1 {
static PrintWriter out;
static StringBuilder sb;
static int n, k;
static long mod = 1000000007;
static int[][] memo;
static String s;
static HashSet<Integer> nodes;
static ArrayList<Integer>[] ad, tree;
static boolean[] vis, taken;
static int[] a;
static TreeSet<Long> al;
static long[] val;
static ArrayList<String> aa;
static char[] b;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] dist = new int[n];
int[] distn = new int[n];
int m = sc.nextInt();
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
int c = sc.nextInt() - 1;
Long[] p = new Long[m+1];
for (int i = 0; i < m; i++)
p[i+1] = sc.nextLong();
p[0]=0l;
Arrays.sort(p);
for (int i = 1; i <= m; i++)
p[i] += p[i - 1];
Queue<Integer> q = new LinkedList<Integer>();
q.add(a);
Arrays.fill(dist, -1);
Arrays.fill(distn, -1);
dist[a] = 0;
distn[b] = 0;
ad = new ArrayList[n];
for (int i = 0; i < n; i++)
ad[i] = new ArrayList<>();
for (int i = 0; i < m; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
ad[x].add(y);
ad[y].add(x);
}
while (!q.isEmpty()) {
int u = q.remove();
for (int v : ad[u]) {
if (dist[v] == -1) {
dist[v] = 1 + dist[u];
q.add(v);
}
}
}
q.add(b);
while (!q.isEmpty()) {
int u = q.remove();
for (int v : ad[u]) {
if (distn[v] == -1) {
distn[v] = 1 + distn[u];
q.add(v);
}
}
}
long ans = Long.MAX_VALUE;
int[] d = new int[n];
q.add(c);
Arrays.fill(d, -1);
d[c] = 0;
while (!q.isEmpty()) {
int u = q.remove();
for (int v : ad[u]) {
if (d[v] == -1) {
d[v] = 1 + d[u];
q.add(v);
}
}
}
if (a == b && b == c) {
out.println(0);
continue;
}
//System.out.println(Arrays.toString(p));
//System.out.println(Arrays.toString(dist));
//System.out.println(Arrays.toString(distn));
// System.out.println(Arrays.toString(d));
for (int i = 0; i < n; i++) {
if (dist[i] + distn[i] + d[i] <= m)
ans = Math.min(ans, p[dist[i] + distn[i] + d[i]] + p[distn[i]]);
}
out.println(ans);
}
out.flush();
}
static class pair implements Comparable<pair> {
int to;
long number;
pair(int t, long n) {
number = n;
to = t;
}
public String toString() {
return to + " " + number;
}
@Override
public int compareTo(pair o) {
return Long.compare(number, o.number);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | 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 | 21fd1da649caad83a26b86841dcbea5b | train_000.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.util.stream.Collectors;
public class Main {
final static int MAXN = 200000 + 5;
static int A;
static int B;
static int C;
static List<Integer>[] G = new List[MAXN];
static int N;
static int M;
static int T;
final static int MOD = 1000000007;
public static void main(String[] args) {
InputReader scanner = new InputReader(System.in);
PrintStream out = new PrintStream(new BufferedOutputStream(System.out));
T = scanner.nextInt();
for (int i = 0; i < T; i++) {
solve(scanner, out);
}
out.flush();
out.close();
}
static int[] bfs(int start) {
int[] dist = new int[N+1];
Arrays.fill(dist, Integer.MAX_VALUE);
List<Integer> q = Arrays.asList(start);
dist[start] = 0;
while (!q.isEmpty()) {
List<Integer> nq = new ArrayList<>();
for (int u: q) {
for (int v: G[u]) {
if (dist[v] > dist[u] + 1) {
dist[v] = dist[u] + 1;
nq.add(v);
}
}
}
q = nq;
}
return dist;
}
static void solve(InputReader scanner, PrintStream out) {
N = scanner.nextInt();
M = scanner.nextInt();
A = scanner.nextInt();
B = scanner.nextInt();
C = scanner.nextInt();
List<Integer> P = new ArrayList<>();
for (int i = 0; i < M; i++) {
int v = scanner.nextInt();
P.add(v);
}
for (int i = 0; i <= N; i++) {
G[i] = new ArrayList<>();
}
for (int i = 0; i < M; i++) {
int u = scanner.nextInt();
int v = scanner.nextInt();
G[u].add(v);
G[v].add(u);
}
int[] dista = bfs(A);
int[] distb = bfs(B);
int[] distc = bfs(C);
P.sort(Integer::compareTo);
long[] presum = new long[M+1];
for (int i = 0; i < M; i++) {
presum[i+1] += presum[i] + P.get(i);
}
long ans = Long.MAX_VALUE;
for (int mid = 1; mid <= N; mid++) {
int da = dista[mid];
int db = distb[mid];
int dc = distc[mid];
if (da + db + dc > M) {
continue;
}
ans = Math.min(ans, presum[da+db+dc] + presum[db]);
}
out.println(ans);
}
static long pow(long a, long b) {
if (a == 0) {
return 0;
}
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long h = pow(a, b / 2);
long ans = h * h;
ans %= MOD;
if (b % 2 != 0) {
ans *= a;
ans %= MOD;
}
return ans;
}
}
class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (this.x != o.x) {
return this.x - o.x;
}
return this.y - o.y;
}
}
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 | 3fd16bdb379bf81e929fe18c0932c5fb | train_000.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 MainClass
{
public static void main(String[] args)throws IOException
{
Reader in = new Reader();
int t = in.nextInt();
StringBuilder stringBuilder = new StringBuilder();
while (t-- > 0)
{
int n = in.nextInt();
int m = in.nextInt();
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int c = in.nextInt() - 1;
long[] P = new long[m];
for (int i=0;i<m;i++)
P[i] = in.nextLong();
new MergeSortLong().sort(P, 0, m - 1);
long[] sum = new long[m];
sum[0] = P[0];
for (int i=1;i<m;i++)
sum[i] = sum[i - 1] + P[i];
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i=0;i<n;i++) adj[i] = new ArrayList<>();
for (int i=0;i<m;i++)
{
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
adj[x].add(y);
adj[y].add(x);
}
int[] fromA = BFS(adj, a);
int[] fromB = BFS(adj, b);
int[] fromC = BFS(adj, c);
long min = Long.MAX_VALUE;
for (int i=0;i<n;i++)
{
int dFromB = fromB[i];
int dFromA = fromA[i];
int dFromC = fromC[i];
long cost = 0L;
if (dFromA + dFromB + dFromC > m)
continue;
if (dFromB > 0)
cost += sum[dFromB - 1];
if (dFromA + dFromB + dFromC > 0)
cost += sum[dFromA + dFromB + dFromC - 1];
if (cost < min)
{
min = cost;
}
}
stringBuilder.append(min ).append("\n");
}
System.out.println(stringBuilder);
}
public static int[] BFS(ArrayList<Integer>[] adj, int v)
{
int[] dist = new int[adj.length];
HashSet<Integer> h = new HashSet<>();
Queue<Integer> nodes = new LinkedList<>();
Queue<Integer> dd = new LinkedList<>();
nodes.add(v);
dd.add(0);
while (!nodes.isEmpty())
{
int node = nodes.poll();
int d = dd.poll();
if (h.contains(node))
continue;
else
{
h.add(node);
dist[node] = d;
for (int u: adj[node])
{
if (!h.contains(u))
{
nodes.add(u);
dd.add(d + 1);
}
}
}
}
return dist;
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
class MergeSortLong
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(long arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(long arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
| 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 | 35cdf60b2ed3316fa37daa10a2bde1bb | train_000.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.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 E_Round_636_Div3 {
public static long MOD = 1000000007;
static int[][] dp;
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 T = in.nextInt();
for (int Z = 0; Z < T; Z++) {
int n = in.nextInt();
int m = in.nextInt();
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
int c = in.nextInt() - 1;
ArrayList<Integer>[] map = new ArrayList[n];
for (int i = 0; i < n; i++) {
map[i] = new ArrayList<>();
}
long[] data = new long[m];
for (int i = 0; i < m; i++) {
data[i] = in.nextInt();
}
Arrays.sort(data);
for (int i = 0; i < m; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
map[u].add(v);
map[v].add(u);
}
int[] A = cal(a, map);
int[] B = cal(b, map);
int[] C = cal(c, map);
long[] pre = new long[m + 1];
for (int i = 1; i < pre.length; i++) {
pre[i] = pre[i - 1] + data[i - 1];
}
long result = Long.MAX_VALUE;
for (int i = 0; i < n; i++) {
int need = A[i] + B[i] + C[i];
if (need <= m) {
long tmp = pre[B[i]] + pre[need];
result = Long.min(result, tmp);
}
}
out.println(result);
}
out.close();
}
static int[] cal(int start, ArrayList<Integer>[] map) {
int n = map.length;
int[] result = new int[n];
Arrays.fill(result, -1);
result[start] = 0;
LinkedList<Integer> q = new LinkedList<>();
q.add(start);
while (!q.isEmpty()) {
int node = q.poll();
for (int i : map[node]) {
if (result[i] == -1) {
result[i] = 1 + result[node];
q.add(i);
}
}
}
return result;
}
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, int b) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
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 | ["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 | 117870fa511efac14b4fedb62afc8677 | train_000.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 WeightsDistributing {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int T = Integer.parseInt(in.readLine());
for(int i = 0; i < T; ++i) {
StringTokenizer st = new StringTokenizer(in.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int A = Integer.parseInt(st.nextToken()) - 1;
int B = Integer.parseInt(st.nextToken()) - 1;
int C = Integer.parseInt(st.nextToken()) - 1;
Integer[] p = new Integer[M];
st = new StringTokenizer(in.readLine());
for(int j = 0; j < M; ++j) {
p[j] = Integer.parseInt(st.nextToken());
}
Arrays.sort(p);
long[] sum = new long[M + 1];
for(int j = 1; j <= M; ++j) {
sum[j] = sum[j - 1] + p[j - 1];
}
List<Integer>[] children = new List[N];
for(int j = 0; j < N; ++j) children[j] = new ArrayList<Integer>();
for(int j = 0; j < M; ++j) {
st = new StringTokenizer(in.readLine());
int a = Integer.parseInt(st.nextToken()) - 1;
int b = Integer.parseInt(st.nextToken()) - 1;
children[a].add(b);
children[b].add(a);
}
int[][] dist = new int[3][N];
for(int j = 0; j < 3; ++j) {
int start = j == 0 ? A : (j == 1 ? B : C);
dist[j] = new int[N];
boolean[] visited = new boolean[N];
Queue<Integer> toVisit = new LinkedList<Integer>();
visited[start] = true;
toVisit.add(start);
while(!toVisit.isEmpty()) {
int node = toVisit.remove();
for(int child : children[node]) {
if(!visited[child]) {
visited[child] = true;
toVisit.add(child);
dist[j][child] = dist[j][node] + 1;
}
}
}
}
long ans = Long.MAX_VALUE;
for(int d = 0; d < N; ++d) {
if(dist[0][d] + dist[1][d] + dist[2][d] > M) continue;
long tot = 2*sum[dist[1][d]] + (sum[Math.min(M, dist[0][d] + dist[1][d] + dist[2][d])] - sum[dist[1][d]]);
ans = Math.min(ans, tot);
}
out.println(ans);
}
in.close();
out.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 | 44e4e101dd8679b6300b783e616ddc6f | train_000.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.*;
public class E {
static int n, m, a, b, c;
static List<List<Integer>> g;
static void bfs(int[] d, int src) {
Queue<Integer> q = new LinkedList<>();
q.offer(src);
int[] vis = new int[n+1];
vis[src] = 1;
while (q.isEmpty() == false) {
int cur = q.poll();
for (int v: g.get(cur)) {
if (vis[v] == 1) continue;
d[v] = d[cur] + 1;
q.offer(v);
vis[v] = 1;
}
}
}
static void runTest(Scanner sc) {
n = sc.nextInt();
m = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
g = new ArrayList<>();
for (int i=0; i<=n; i++) g.add(new ArrayList<>());
int p[] = new int[m];
for (int i=0; i<m; i++) p[i] = sc.nextInt();
for (int i=1; i<=m; i++) {
int u, v;
u = sc.nextInt();
v = sc.nextInt();
u--;
v--;
g.get(u).add(v);
g.get(v).add(u);
}
int da[] = new int[n+1];
int db[] = new int[n+1];
int dc[] = new int[n+1];
bfs(da, a-1);
bfs(db, b-1);
bfs(dc, c-1);
long ans = (long)1e16;
Arrays.sort(p);
long pre[] = new long[m+1];
for (int i=0; i<m; i++) pre[i+1] = pre[i] + p[i];
for (int i=0; i<n; i++) {
if (da[i] + db[i] + dc[i] > m) continue;
// System.out.println(i + " " + da[i] + " " + db[i] + " " + dc[i]);
ans = Math.min(ans, pre[db[i]] + pre[da[i] + db[i] + dc[i]]);
}
System.out.println(ans);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int tests = sc.nextInt();
while (tests-- > 0) {
runTest(sc);
}
}
} | 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 | 6b190ca05058405fdece91ef0522bd12 | train_000.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 e636 {
static PrintWriter out;
static BufferedReader in;
static StringTokenizer st;
public static void main(String[] args) throws FileNotFoundException {
//out = new PrintWriter("test.out");
//in = new BufferedReader(new FileReader("test.in"));
out = new PrintWriter(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
new e636().Run();
out.close();
}
String ns() {
try {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
} catch (Exception e) {
return null;
}
}
int nextint() {
return Integer.valueOf(ns());
}
int N, n, m, a, b, c, distSum;
ArrayList<Integer> [] adj;
int [] price;
long [] psprice;
long res;
int inf = Integer.MAX_VALUE;
int [] distax;
int [] distbx;
int [] distcx;
public void Run() {
N = nextint();
while (N-- > 0) {
{
n = nextint();
m = nextint();
a = nextint() - 1;
b = nextint() - 1;
c = nextint() - 1;
price = new int[m];
for (int i = 0; i < m; i++) {
price[i] = nextint();
}
Arrays.sort(price);
psprice = new long [m+1];
for(int i = 0 ; i < m; i++){
psprice[i+1] = psprice[i] + price[i];
}
adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int q = nextint() - 1;
int w = nextint() - 1;
adj[q].add(w);
adj[w].add(q);
}
}
distax = distbx = distcx = new int[n];
distax = bfs(a);
distbx = bfs(b);
distcx = bfs(c);
res = Long.MAX_VALUE;
for(int i = 0 ; i < n; i++){
if (distax[i] + distbx[i] + distcx[i] <= m) {
res = Math.min(res,
psprice[distbx[i]] +
psprice[distax[i] +
distbx[i] +
distcx[i]]
);
}
}
out.print(res + " " + '\n');
}
}
void cs(int [] dist, boolean [] vis){
Arrays.fill(vis, false);
Arrays.fill(dist, 0);
}
int[] bfs(int start){
int [] dist = new int [n];
boolean [] vis = new boolean [n];
cs(dist, vis);
Queue<Integer> q = new LinkedList();
q.add(start);
while(q.size() > 0){
int c = q.poll();
vis[c] = true;
for(int i : adj[c]){
if(!vis[i]){
vis[i]=true;
dist[i] = dist[c]+1;
q.add(i);
}
}
}
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 | 0f4a85d265f390229103e7a3413edefc | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
public class PrimeMatrix {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static void solve() throws Exception {
List<Integer> list = getPrime();
int n = nextInt();
int m = nextInt();
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (ans == 0)
break;
int t = 0;
for (int j = 0; j < m; j++) {
int index = Collections.binarySearch(list, matrix[i][j]);
if (index < 0)
t += list.get(-index - 1) - matrix[i][j];
}
ans = Math.min(ans, t);
}
for (int j = 0; j < m; j++) {
if (ans == 0)
break;
int t = 0;
for (int i = 0; i < n; i++) {
int index = Collections.binarySearch(list, matrix[i][j]);
if (index < 0)
t += list.get(-index - 1) - matrix[i][j];
}
ans = Math.min(ans, t);
}
out.println(ans);
}
static List<Integer> getPrime() {
int max = 200000;
boolean[] b = new boolean[max + 1];
for (int i = 2; i * i <= max; i++)
if (!b[i])
for (int j = i * i; j <= max; j += i)
b[j] = true;
List<Integer> list = new ArrayList<>();
for (int i = 2; i <= max; i++)
if (!b[i])
list.add(i);
return list;
}
public static void main(String args[]) {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static int[] nextIntArray(int len, int start) throws IOException {
int[] a = new int[len];
for (int i = start; i < len; i++)
a[i] = nextInt();
return a;
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static long[] nextLongArray(int len, int start) throws IOException {
long[] a = new long[len];
for (int i = start; i < len; i++)
a[i] = nextLong();
return a;
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static double[] nextDoubleArray(int len, int start) throws IOException {
double[] a = new double[len];
for (int i = start; i < len; i++)
a[i] = nextDouble();
return a;
}
static BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
static String next() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static String nextLine() throws IOException {
tok = new StringTokenizer("");
return in.readLine();
}
static void shuffleArray(long[] array) {
Random random = new Random();
for (int i = array.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
long temp = array[index];
array[index] = array[i];
array[i] = temp;
}
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 70a086d68d3c61ff8852f53806772cfd | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Set;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.Vector;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main implements Runnable{
static {
}
public static void main(String[] args) throws IOException {
new Thread(null , new Main(),"Main", 1<<26).start();
}
public void run(){
try {
PrintWriter out = new PrintWriter(System.out);
MyScanner sc = new MyScanner();
solve(out, sc);
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
void solve(PrintWriter out, MyScanner sc){
int max = (int)1e5;
int n = sc.nextInt();
int m = sc.nextInt();
int[][] a = new int[n][m];
for(int i = 0; i < n ; ++i) {
for(int j = 0 ; j < m; ++j) {
a[i][j] = sc.nextInt();
}
}
boolean[] prime = new boolean[max + 10];
Arrays.fill(prime, true);
prime[0] = prime[1] = false;
for(int i = 2 ; i * i <= max + 5; ++i ) {
if(prime[i]) {
for(int k = i + i ; k <= max + 5;k += i) {
prime[k] = false;
}
}
}
long min = Long.MAX_VALUE;
long sum = 0;
for(int i = 0 ; i < n ; ++i) {
sum = 0;
for(int j = 0 ; j < m ; ++j) {
for(int k = a[i][j] ; ; ++k) {
if(prime[k]) {
sum += (k - a[i][j]);
break;
}
}
}
min = Math.min(min, sum);
}
for(int j = 0 ; j < m ; ++j) {
sum = 0;
for(int i = 0 ; i < n ; ++i) {
for(int k = a[i][j] ; ; ++k) {
if(prime[k]) {
sum += (k - a[i][j]);
break;
}
}
}
min = Math.min(min, sum);
}
out.print(min);
}
class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 93fd3b76fb098fba018103a5eb9c1038 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class TaskC {
static Integer[][]dp;
static int n, m, ans;
static String s;
static TreeSet<Integer> primes;
static void generatePrimes()
{
primes = new TreeSet<>();
primes.add(2);
for (int i = 3 ; i <= (1e6) ; i++,++i)
{
int j = 2;
boolean isPrime = true;
while (1l*j*j <= i)
{
if(i%j == 0)
{
isPrime = false;
break;
}
j++;
}
if(isPrime)primes.add(i);
}
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
generatePrimes();
int n = sc.nextInt();
int m = sc.nextInt();
int[][]arr = new int[n][m];
int[][]dis = new int[n][m];
for (int i = 0 ; i < n ; i ++)
{
for (int j = 0 ; j < m ; j++) {
int a = sc.nextInt();
Integer ceil = primes.ceiling(a);
if (primes.contains(a))
dis[i][j] = 0;
else
dis[i][j] = (Math.abs(a - ceil));
}
}
/* for (int i = 0 ; i < n ; i++)
System.out.println(Arrays.toString(dis[i]));*/
int ans = Integer.MAX_VALUE;
for (int i = 0 ; i < n ; i ++)
{
int tmp = 0;
for (int j = 0 ; j < m ; j++)
{
tmp+=dis[i][j];
}
ans = Math.min(tmp , ans);
}
for (int j = 0 ; j < m ; j ++)
{
int tmp = 0;
for (int i = 0 ; i < n ; i++)
{
tmp+=dis[i][j];
}
ans = Math.min(tmp , ans);
}
pw.print(ans);
pw.close();
}
private static long gcd(long a, long b) {
if( b == 0)
return a;
return gcd(b , a%b);
}
static long lcm(int a, int b)
{
return (a*b)/gcd(a, b);
}
private static int dis(int xa , int ya , int xb , int yb)
{
return (xa-xb)*(xa - xb) + (ya- yb)*(ya-yb);
}
static class Pair implements Comparable<Pair> {
double x,y;
public Pair(double x, double y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
/* if (x == o.x)
return y - o.y;
return x - o.x;*/
return 0;
}
public double dis(Pair a){
return (a.x - x)*(a.x - x) + (a.y-y)*(a.y-y);
}
public String toString() {
return x+" "+ y;
}
public boolean overlap(Pair a)
{
if((this.x >= a.x && this.x <= a.y) || (a.x >= this.x && a.x <= this.y)) return true;
return false;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public boolean check() {
if (!st.hasMoreTokens())
return false;
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public double nextDouble() {
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() {
try {
return br.ready();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | ef00b04f0d4e945952317af44318e0da | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.util.*;
public class PrimeMatrix {
public static int prime[] = new int[1000000+100];
public static int state[]= new int[1000000+100];
public static int total=1;
public static void main(String[] args) {
int number=1000000;
sieve(number);
Scanner in = new Scanner(System.in);
int n= in.nextInt();
int m= in.nextInt();
int min=100000000;
int ara[][]= new int[n+2][m+2];
for(int i=0;i<n;i++){
int ans=0;
for(int j=0;j<m;j++){
ara[i][j]=in.nextInt();
int t=binary_search(ara[i][j]);
ans+=t;
}
min=Math.min(ans,min);
}
for(int i=0;i<m;i++){
int ans=0;
for(int j=0;j<n;j++){
ans+=binary_search(ara[j][i]);
}
min=Math.min(ans,min);
}
System.out.println(min);
}
public static void sieve(int n){
int z=(int)Math.sqrt(n);
for(int i=3;i<=z;i+=2){
if(state[i]==0){
for(int j=i*i;j<=n;j+=i*2)
state[j]=1;
}
}
prime[0]=2;
for(int i=3;i<=n;i+=2){
if(state[i]==0){
prime[total]=i;
total++;
}
}
}
public static int binary_search(int n){
int high=total-1;
int low=0;
int ans=0;
while(low<=high){
int mid=(high+low)/2;
if(prime[mid]>=n){
ans=prime[mid];
high=mid-1;
}
else low=mid+1;
}
if(n<=ans) return ans-n;
else return n-ans;
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | ced662943613c05f8afdf01b65c4e68d | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.util.Scanner;
public class PrimeMatrix
{
static int [] primes;
static int [] bs;
static final int SIZE = 9593;
static final int INF = (int) 1e9;
static void sieve(int n)
{
bs = new int[n+1];
primes = new int[SIZE];
bs[0] = bs[1] = 1;
int idx = 0;
for (int i = 2; i < bs.length; i++)
{
if(bs[i] == 0)
{
if(i < 1000)
for (int j = i*i; j < bs.length; j+= i)
{
bs[j] = 1;
}
primes[idx++] = i;
}
}
}
static int nearPrime(int n)
{
int start = 0, end = SIZE;
int ans = INF;
int ansIdx = -1;
while(start < end)
{
int mid = start + (end - start)/2 ;
int cur = primes[mid];
if(cur == n)
{
return n;
}
if(cur > n)
{
if(cur < ans)
{
ans = cur;
ansIdx = mid;
}
end = ansIdx;
}
else
{
start = mid+1;
}
}
return ans;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
sieve(100003);
int n = sc.nextInt();
int m =sc.nextInt();
int[][] grid = new int[n][m];
int[][] diff = new int[n][m];
int ans = INF;
for (int i = 0; i < n; i++)
{
int sumRow = 0;
for (int j = 0; j < m; j++)
{
int cur = sc.nextInt();
grid[i][j] = cur;
diff[i][j] = nearPrime(cur) - cur;
sumRow += diff[i][j];
}
if(sumRow < ans)
ans = sumRow;
}
for (int i = 0; i < m; i++)
{
int sumCol = 0;
for (int j = 0; j < n; j++)
{
sumCol += diff[j][i];
}
if(sumCol < ans)
ans = sumCol;
}
System.out.println(ans);
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 0035836b379058c007f8bcb69e132f4b | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 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 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.ni(), m = in.ni();
int[] r = new int[n], c = new int[m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int next = in.ni();
int diff = findNextPrime(next) - next;
r[i] += diff;
c[j] += diff;
}
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (r[i] < min) {
min = r[i];
}
}
for (int i = 0; i < m; i++) {
if (c[i] < min) {
min = c[i];
}
}
out.println(min);
}
private int findNextPrime(int x) {
while (!isPrime(x)) {
x++;
}
return x;
}
private boolean isPrime(int x) {
if (x == 2) return true;
if (x == 1 || x % 2 == 0) return false;
for (int i = 3; i * i <= x; i += 2) {
if (x % i == 0) return false;
}
return true;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 91df1b280e316dedab5210ed36620095 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 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 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.ni(), m = in.ni();
int[] r = new int[n], c = new int[m];
int[] found = new int[100001];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int next = in.ni();
if (found[next] == 0) {
found[next] = findNextPrime(next);
}
int diff = found[next] - next;
r[i] += diff;
c[j] += diff;
}
}
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (r[i] < min) {
min = r[i];
}
}
for (int i = 0; i < m; i++) {
if (c[i] < min) {
min = c[i];
}
}
out.println(min);
}
private int findNextPrime(int x) {
while (!isPrime(x)) {
x++;
}
return x;
}
private boolean isPrime(int x) {
if (x == 2) return true;
if (x == 1 || x % 2 == 0) return false;
for (int i = 3; i * i <= x; i += 2) {
if (x % i == 0) return false;
}
return true;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 5ab1ba9c97d4309380193656697034a7 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean [] prime = new boolean[250000];
for(int i=0;i<250000;i++)
prime[i] = true;
prime[0]=prime[1]=false;
for(int i=2;i<250000;i++)
if(prime[i])
for(int j=i+i;j<250000;j+=i)
prime[j] = false;
int n=in.nextInt();
int m=in.nextInt();
int []row=new int [n];
int []col=new int [m];
int [][] a=new int [n][m];
int [][] c=new int [n][m];
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
a[i][j]=in.nextInt();
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
while(true){
if(prime[a[i][j]]==true)
break;
else {
a[i][j]++;
c[i][j]++;
}
}
for(int j=0;j<n;j++)
for(int i=0;i<m;i++)
row[j]+=c[j][i];
for(int j=0;j<m;j++)
for(int i=0;i<n;i++)
col[j]+=c[i][j];
Arrays.sort(row);
Arrays.sort(col);
if(row[0]<=col[0])
System.out.println(row[0]);
else
System.out.println(col[0]);
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 662cb258e44d81643f73bb8093b37556 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes |
import java.io.*;
import java.util.*;
public class CF {
public static void main(String[] args) throws IOException {
//FastScanner in = new FastScanner(new FileInputStream(new File("input.txt")));
//PrintWriter out = new PrintWriter(new File("output.txt"));
FastScanner in = new FastScanner(System.in);
boolean[] primes = new boolean[200000];
Arrays.fill(primes, true);
primes[0] = primes[1] = false;
for (int i = 2; i < primes.length; i++) {
if (primes[i]) {
for (int j = 2 * i; j < primes.length; j += i) {
primes[j] = false;
}
}
}
int n = in.nextInt();
int m = in.nextInt();
int[][] mat = new int[n][m];
for (int i = 0; i < n; i++) {
mat[i] = in.nextArrayInt(m);
}
int maxPrimes = 0;
int minOp = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
int nbOp = 0;
for (int j = 0; j < m; j++) {
int c = mat[i][j];
while (!primes[c]) {
c++;
}
nbOp += c - mat[i][j];
}
minOp = Integer.min(minOp, nbOp);
}
for (int i = 0; i < m; i++) {
int nbOp = 0;
for (int j = 0; j < n; j++) {
int c = mat[j][i];
while (!primes[c]) {
c++;
}
nbOp += c - mat[j][i];
}
minOp = Integer.min(minOp, nbOp);
}
System.out.println(minOp);
}
public static long num = 0;
public static String[] edges = {"A", "B", "C", "D"};
public static void recurcive(int k, int n, int lastIndex) {
if (k == n) {
num++;
return;
}
for (int i = 0; i < 4; i++) {
if (i != lastIndex) {
if (k == n - 1 && i == 3) {
break;
}
recurcive(k + 1, n, i);
}
}
}
public static ArrayList<Long> listCh = new ArrayList<>();
public static String[] tabCh = {"4", "7"};
public static void permutLucky(int i, String ch) {
if (i == 11) {
return;
}
for (int j = 0; j < tabCh.length; j++) {
String string = ch + tabCh[j];
listCh.add(Long.valueOf(string));
permutLucky(i + 1, string);
}
}
public static int sumTable(int[] tab, int indx) {
if (indx == tab.length) {
return 0;
}
return tab[indx] + sumTable(tab, indx + 1);
}
public static List<int[]> list = new LinkedList<>();
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
int[] tab = new int[size];
for (int i = 0; i < tab.length; i++) {
tab[i] = input[i];
}
list.add(tab);
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
int temp2 = input[i];
input[i] = input[startindex];
input[startindex] = temp2;
}
}
}
public static int[] radixSort(int[] f) {
return radixSort(f, f.length);
}
public static int[] radixSort(int[] f, int n) {
int[] to = new int[n];
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) {
b[1 + (f[i] & 0xffff)]++;
}
for (int i = 1; i <= 65536; i++) {
b[i] += b[i - 1];
}
for (int i = 0; i < n; i++) {
to[b[f[i] & 0xffff]++] = f[i];
}
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < n; i++) {
b[1 + (f[i] >>> 16)]++;
}
for (int i = 1; i <= 65536; i++) {
b[i] += b[i - 1];
}
for (int i = 0; i < n; i++) {
to[b[f[i] >>> 16]++] = f[i];
}
int[] d = f;
f = to;
to = d;
}
return f;
}
private static class FastScanner {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
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++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextArrayInt(int n) {
int tab[] = new int[n];
for (int i = 0; i < n; i++) {
tab[i] = nextInt();
}
return tab;
}
public String[] nextArrayString(int n) {
String tab[] = new String[n];
for (int i = 0; i < n; i++) {
tab[i] = next();
}
return tab;
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 06df0ce0192e5cc82ba7b10e2963f9a4 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes |
/*
*
* Date: 07 September 2019
* Time: 01:03:00
*/
import java.io.*;
import java.util.*;
public class pm
{
static int p[]=new int[10454];
static void seive(){
int n=110005;
boolean prime[]=new boolean[n+1];
Arrays.fill(prime,true);
prime[0]=false;
prime[1]=false;
for(int i=2;i*i<=n;i++){
if(prime[i]){
for(int j=i*i;j<=n;j+=i){
prime[j]=false;
}
}
}
int cnt=0;
int j=0;
for(int i=1;i<n;i++){
if(prime[i]){
// System.out.print(i+" ");
p[j]=i;
j++;
//cnt++;
}
}
// System.out.println(cnt);
}
static int search(int tar){
int l=0,r=10454;
while(l<r){
int mid = l + (r - l)/2;
if(p[mid]>=tar){
r=mid;
}else{
l=mid+1;
}
}
return l;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
seive();
int n=sc.nextInt();
int m=sc.nextInt();
HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>();
int arr[][]=new int[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
arr[i][j]=sc.nextInt();
int idx=search(arr[i][j]);
hm.put(arr[i][j],p[idx]-arr[i][j]);
}
}
int min=Integer.MAX_VALUE;
for(int i=0;i<n;i++){
int sum=0;
for(int j=0;j<m;j++){
sum+=hm.get(arr[i][j]);
}
if(sum<min){
min=sum;
}
}
for(int j=0;j<m;j++){
int sum=0;
for(int i=0;i<n;i++){
sum+=hm.get(arr[i][j]);
}
if(sum<min){
min=sum;
}
}
System.out.println(min);
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 21a839df67072a11a02bb5057f9d9282 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.util.*;
public class CodeForces
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
int[][] array = new int[n][m];
int[] next = new int[100100];
boolean[] primes = sieveOfEratosthenes(1000100);
int min = Integer.MAX_VALUE;
for (int i = 0; i < n; i++)
{
int count = 0;
for (int j = 0; j < m; j++)
{
array[i][j] = input.nextInt();
if (next[array[i][j]] > 0)
{
count += (next[array[i][j]] - array[i][j]);
} else
{
int z = array[i][j];
int stop = 0;
if (z == 1)
{
count++;
stop = 2;
} else if (z == 2)
{
stop = 2;
} else if (z % 2 == 0)
{
z++;
count++;
while (!primes[z])
{
z += 2;
count += 2;
stop = z;
}
} else
{
while (!primes[z])
{
z++;
count++;
stop = z;
}
}
next[z] = stop;
}
}
if (count < min)
{
min = count;
}
}
for (int i = 0; i < m; i++)
{
int count = 0;
for (int j = 0; j < n; j++)
{
if (next[array[j][i]] > 0)
{
count += (next[array[j][i]] - array[j][i]);
} else
{
int z = array[j][i];
int stop = 0;
if (z == 1)
{
count++;
stop = 2;
} else if (z == 2)
{
stop = 2;
} else if (z % 2 == 0)
{
z++;
count++;
while (!primes[z])
{
z += 2;
count += 2;
stop = z;
}
} else
{
while (!primes[z])
{
z++;
count++;
stop = z;
}
}
next[z] = stop;
}
}
if (count < min)
{
min = count;
}
}
System.out.println(min);
}
public static boolean[] sieveOfEratosthenes(int n)
{
boolean prime[] = new boolean[n + 1];
for (int i = 0; i < n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
if (prime[p] == true)
{
for (int i = p * 2; i <= n; i += p)
prime[i] = false;
}
}
prime[0] = false;
prime[1] = false;
return prime;
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 2b3157f59a91880b71d76dccc877612f | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.util.*;
import java.util.Scanner;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.lang.model.util.ElementScanner6;
public class B271
{
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;
}
}
static int gcd(int a,int b)
{
if(a==0)
return b;
return gcd(a%b,b);
}
static int lcm(int a,int b)
{
return (a*b)/gcd(a,b);
}
static boolean prime[];
static ArrayList<Integer> al;
static void sieveofe()
{
int n=1000000;
al=new ArrayList<>();
prime=new boolean[n+1];
Arrays.fill(prime,true);
prime[1]=false;
for(int i=2;i*i<=n;i++)
{
if(prime[i]==true)
{
for(int j=i*i;j<=n;j+=i)
{
prime[j]=false;
}
}
}
for(int i=2;i<=n;i++)
{
if(prime[i])al.add(i);
}
Collections.sort(al);
}
static int upbound(int x)
{
int lo=0;
int hi=al.size()-1;
int ans=-1;
while(lo<=hi)
{
int mid=lo+(hi-lo)/2;
if(al.get(mid)>=x)
{
hi=mid-1;
ans=al.get(mid);
}
else
{
lo=mid+1;
}
}
return ans;
}
public static void main(String args[])
{
FastReader in=new FastReader();
PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t=1;
//t=in.nextInt();
sieveofe();
while(t-->0)
{
int n=in.nextInt();
int m=in.nextInt();
int arr[][]=new int[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
arr[i][j]=in.nextInt();
}
}
long ans=Long.MAX_VALUE;
for(int i=0;i<n;i++)
{
long cost=0;
for(int j=0;j<m;j++)
{
if(!prime[arr[i][j]])
{
cost+=upbound(arr[i][j])-arr[i][j];
}
}
ans=Math.min(ans,cost);
}
for(int i=0;i<m;i++)
{
long cost=0;
for(int j=0;j<n;j++)
{
if(!prime[arr[j][i]])
{
cost+=upbound(arr[j][i])-arr[j][i];
}
}
ans=Math.min(ans,cost);
}
pr.println(ans);
pr.flush();
}
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 51f262a555f1a2c124785812f842e0e6 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.awt.*;
import java.io.*;
import java.util.*;
public class AA implements Runnable {
public void run() {
InputReader sc = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int i=0,j=0,k=0;
int t=0;
//t=sc.nextInt();
while (t-->0)
{
}
int max=100004;
boolean iscomposite[]=new boolean[max];
iscomposite[0]=true;
iscomposite[1]=true;
int curr=2;
while (curr*curr<max)
{
if (!iscomposite[curr])
{
j=curr;
while (curr*j<max)
{
iscomposite[curr*j]=true;
j++;
}
}
curr++;
}
int rows=sc.nextInt();
int cols=sc.nextInt();
int arr[][]=new int[rows][cols];
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
int temp=sc.nextInt();
int count=0;
while (iscomposite[temp])
{
count++;
temp++;
}
arr[i][j]=count;
}
}
max=Integer.MAX_VALUE;
for (i=0;i<rows;i++)
{
int tempmax=0;
for (j=0;j<cols;j++)
{
tempmax+=arr[i][j];
}
max=Math.min(max,tempmax);
}
for (i=0;i<cols;i++)
{
int tempmax=0;
for (j=0;j<rows;j++)
{
tempmax+=arr[j][i];
}
max=Math.min(max,tempmax);
}
out.println(max);
//=======================================================================================================================================
out.flush();
out.close();
}
//=======================================================================================================================================
static boolean isValid(Pair x,int n,int m)
{
return x.a>=0 && x.a<n && x.b>=0 && x.b<m;
}
static int dx[]={0,0,1,-1};
static int dy[]={1,-1,0,0};
static class Pair
{
int a,b;
Pair(int aa,int bb)
{
a=aa;
b=bb;
}
public String toString()
{
return a+" "+b;
}
}
int sa(int a[],InputReader sc)
{
int x=0;
for(int i=0;i<a.length;i++)
{
x+=a[i]=sc.nextInt();
}
return x;
}
static class PairSort implements Comparator<Pair>
{
public int compare(Pair a,Pair b)
{
return b.b-a.b;
}
}
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 AA(),"Main",1<<27).start();
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | fb1b60b3bd86c635e9ffac8e134f25a7 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static ArrayList<Integer> prime;
public static void sieve()
{
boolean[] isPrime = new boolean[(int)1e6];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for(int i = 2;i<isPrime.length;i++)
{
if(isPrime[i])
{
for(int j = i<<1;j<isPrime.length;j+=i)
{
isPrime[j] = false;
}
}
}
prime = new ArrayList<Integer>();
for (int i = 2; i < isPrime.length; i++) {
if(isPrime[i])
prime.add(i);
}
}
public static int bs(int n)
{
int lo = 0,hi=prime.size();
int ans = 0;
while(lo<=hi)
{
int mid = lo + (hi-lo)/2;
int cur = prime.get(mid);
if(cur>=n)
{
hi = mid-1;
ans = cur;
}
else
{
lo = mid+1;
}
}
return ans!=0?ans:n;
}
public static void main(String[] args) throws Throwable
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
{
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++)
{
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
sieve();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++)
{
int cur = 0;
for (int j = 0; j < m; j++)
{
int maxPrime = bs(arr[i][j]);
cur += maxPrime-arr[i][j];
}
ans = Math.min(ans,cur);
}
for (int i = 0; i < m; i++)
{
int cur = 0;
for (int j = 0; j < n; j++)
{
int maxPrime = bs(arr[j][i]);
cur += maxPrime-arr[j][i];
}
ans = Math.min(ans,cur);
}
System.out.println(ans);
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 0d931d94a8ab923de5d52d22aaeb5cd8 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static ArrayList<Integer> prime;
public static void sieve()
{
boolean[] isPrime = new boolean[(int)1e6];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for(int i = 2;i<isPrime.length;i++)
{
if(isPrime[i])
{
for(int j = i<<1;j<isPrime.length;j+=i)
{
isPrime[j] = false;
}
}
}
prime = new ArrayList<Integer>();
for (int i = 2; i < isPrime.length; i++) {
if(isPrime[i])
prime.add(i);
}
}
public static int bs(int n)
{
int lo = 0,hi=prime.size();
int ans = 0;
while(lo<=hi)
{
int mid = lo + (hi-lo)/2;
int cur = prime.get(mid);
if(cur>=n)
{
hi = mid-1;
ans = cur;
}
else
{
lo = mid+1;
}
}
return ans!=0?ans:n;
}
public static void main(String[] args) throws Throwable
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++)
{
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++)
{
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
sieve();
int ans = Integer.MAX_VALUE;
for (int i = 0; i < n; i++)
{
int cur = 0;
for (int j = 0; j < m; j++)
{
int maxPrime = bs(arr[i][j]);
cur += maxPrime-arr[i][j];
}
ans = Math.min(ans,cur);
}
for (int i = 0; i < m; i++)
{
int cur = 0;
for (int j = 0; j < n; j++)
{
int maxPrime = bs(arr[j][i]);
cur += maxPrime-arr[j][i];
}
ans = Math.min(ans,cur);
}
System.out.println(ans);
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | c2aef36d5c7d542e0094681361114732 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.util.*;
public class main {
public static ArrayList<Integer> sieve(int n){
boolean[] primeBoolArray = new boolean[n+1];
Arrays.fill(primeBoolArray, true);
ArrayList<Integer> myPrimes = new ArrayList<Integer>(n+1);
primeBoolArray[0] = false;
primeBoolArray[1] = false;
for(int currNumber = 2; currNumber < n; currNumber++) {
if(primeBoolArray[currNumber] == true) {
myPrimes.add(currNumber);
for(int i = (2*currNumber); i < n; i += currNumber) {
primeBoolArray[i] = false;
}
}
}
return myPrimes;
}
public static int binarySearch(List<Integer> primeList, int start, int end, int value){
if (end >= start){
int mid = (start + end)/2;
if(primeList.get(mid) == value) {
return value;
}else if(primeList.get(mid) < value) {
return binarySearch(primeList, mid+1, end, value);
} else {
return binarySearch(primeList, start, mid-1, value);
}
}
if(start < primeList.size()) {
return primeList.get(start);
}
return -1;
}
public static void main(String[] args) {
ArrayList<Integer> allPrimes = sieve(200001);
Scanner sc = new Scanner(System.in);
int matrixRows = sc.nextInt();
int matrixCols = sc.nextInt();
int[][] myMatrix = new int[matrixRows][matrixCols];
for(int currRow = 0; currRow < matrixRows; currRow++) {
for(int currCol = 0; currCol < matrixCols; currCol++) {
myMatrix[currRow][currCol] = sc.nextInt();
}
}
int[] rowsValue = new int[matrixRows];
int[] colsValue = new int[matrixCols];
for(int currRow = 0; currRow < matrixRows; currRow++) {
for(int currCol = 0; currCol < matrixCols; currCol++) {
int currNumber = myMatrix[currRow][currCol];
int smallestPrime = binarySearch(allPrimes, 0, allPrimes.size()-1, currNumber);
int primeDiff = smallestPrime - currNumber;
rowsValue[currRow] += primeDiff;
}
}
for(int currCol = 0; currCol < matrixCols; currCol++) {
for(int currRow = 0; currRow < matrixRows; currRow++) {
int currNumber = myMatrix[currRow][currCol];
int smallestPrime = binarySearch(allPrimes, 0, allPrimes.size()-1, currNumber);
int primeDiff = smallestPrime - currNumber;
colsValue[currCol] += primeDiff;
}
}
int minRowValue = Arrays.stream(rowsValue).min().getAsInt();
int minColValue = Arrays.stream(colsValue).min().getAsInt();
if(minRowValue < minColValue) {
System.out.print(minRowValue);
} else {
System.out.print(minColValue);
}
}
} | Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output | |
PASSED | 910326ed8ac1806b4bc2a096bc1bc607 | train_000.jsonl | 1360596600 | You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.You are really curious about prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors: itself and number one. For example, numbers 2, 3, 5 are prime and numbers 1, 4, 6 are not. A matrix is prime if at least one of the two following conditions fulfills: the matrix has a row with prime numbers only; the matrix has a column with prime numbers only; Your task is to count the minimum number of moves needed to get a prime matrix from the one you've got. | 256 megabytes | import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class P271B {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int[][] arr = new int[n][m];
for (int r = 0; r < n; r++) {
for (int c = 0; c < m; c++) {
arr[r][c] = s.nextInt();
}
}
boolean[] prime = new boolean[101001];
Arrays.fill(prime, true);
int[] primes = new int[101000];
int index = 0;
for (int i = 2; i < 101001; i++) {
if (prime[i]) {
primes[index++] = i;
int mult = 2;
while (i * mult < 101001) {
prime[i * mult++] = false;
}
}
}
HashMap<Integer, Integer> toPrime = new HashMap<>();
int current = 0;
for (int i = 1; i < 100001; i++) {
if (i > primes[current]) current++;
toPrime.put(i, primes[current] - i);
}
int min = Integer.MAX_VALUE;
for (int r = 0; r < n; r++) {
int rowSum = 0;
for (int c = 0; c < m; c++) {
rowSum += toPrime.get(arr[r][c]);
}
min = Math.min(min, rowSum);
}
for (int c = 0; c < m; c++) {
int colSum = 0;
for (int r = 0; r < n; r++) {
colSum += toPrime.get(arr[r][c]);
}
min = Math.min(min, colSum);
}
System.out.println(min);
}
}
| Java | ["3 3\n1 2 3\n5 6 1\n4 4 1", "2 3\n4 8 8\n9 2 9", "2 2\n1 3\n4 2"] | 2 seconds | ["1", "3", "0"] | NoteIn the first sample you need to increase number 1 in cell (1, 1). Thus, the first row will consist of prime numbers: 2, 2, 3.In the second sample you need to increase number 8 in cell (1, 2) three times. Thus, the second column will consist of prime numbers: 11, 2.In the third sample you don't have to do anything as the second column already consists of prime numbers: 3, 2. | Java 8 | standard input | [
"binary search",
"number theory",
"brute force",
"math"
] | d549f70d028a884f0313743c09c685f1 | The first line contains two integers n, m (1 ≤ n, m ≤ 500) — the number of rows and columns in the matrix, correspondingly. Each of the following n lines contains m integers — the initial matrix. All matrix elements are positive integers. All numbers in the initial matrix do not exceed 105. The numbers in the lines are separated by single spaces. | 1,300 | Print a single integer — the minimum number of moves needed to get a prime matrix from the one you've got. If you've got a prime matrix, print 0. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.