exec_outcome
stringclasses
1 value
code_uid
stringlengths
32
32
file_name
stringclasses
111 values
prob_desc_created_at
stringlengths
10
10
prob_desc_description
stringlengths
63
3.8k
prob_desc_memory_limit
stringclasses
18 values
source_code
stringlengths
117
65.5k
lang_cluster
stringclasses
1 value
prob_desc_sample_inputs
stringlengths
2
802
prob_desc_time_limit
stringclasses
27 values
prob_desc_sample_outputs
stringlengths
2
796
prob_desc_notes
stringlengths
4
3k
lang
stringclasses
5 values
prob_desc_input_from
stringclasses
3 values
tags
listlengths
0
11
src_uid
stringlengths
32
32
prob_desc_input_spec
stringlengths
28
2.37k
difficulty
int64
-1
3.5k
prob_desc_output_spec
stringlengths
17
1.47k
prob_desc_output_to
stringclasses
3 values
hidden_unit_tests
stringclasses
1 value
PASSED
fe33a189836f413b91bb7a0873654497
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.awt.*; import java.io.*; import java.util.*; public class Abc { static int dp[][],n,arr[][]; public static void main(String[] args) { FastReader sc = new FastReader(); n=sc.nextInt(); arr=new int[n][3]; dp=new int[n][2]; for (int i=0;i<n;i++){ arr[i][0]=sc.nextInt(); } for (int i=0;i<n;i++){ arr[i][1]=sc.nextInt(); } for (int i=0;i<n;i++){ arr[i][2]=sc.nextInt(); } for (int arr[]:dp){ Arrays.fill(arr,-1); } System.out.println(dp(0,0)); } static int dp(int i,int st){ if (i==n-1 && st==0)return arr[i][0]; if (i==n-1 && st==1)return arr[i][1]; if (dp[i][st]!=-1)return dp[i][st]; if (st==1){ return dp[i][1]=Math.max(dp(i+1,0)+arr[i][2],dp(i+1,1)+arr[i][1]); }else { return dp[i][0]=Math.max(dp(i+1,1)+arr[i][0],dp(i+1,0)+arr[i][1]); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
a4dfa9eae6f61faeeb83b160c467d8a4
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; public class Main { static long mod = 1000000007; static int size = 200000; static long[] fac = new long[size]; static long[] finv = new long[size]; static long[] inv = new long[size]; static int INF = Integer.MAX_VALUE; //Dima and Hares public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] a = new int[n+1]; int[] b = new int[n+1]; int[] c = new int[n+1]; for(int i = 1; i <= n; i++){ a[i] = scanner.nextInt(); //どっちもお腹空いてる } for(int i = 1; i <= n; i++){ b[i] = scanner.nextInt(); //片方お腹空いてる } for(int i = 1; i <= n; i++){ c[i] = scanner.nextInt(); //どっちもお腹いっぱい } if(n == 1){ System.out.println(a[1]); return; } //dp[i][j]:= i番目までのうさぎに餌をあげる時、i+1番目のうさぎが //既にj:0 餌をもらっていない、j:1餌をもらっている時の満足度の合計の最大値 int[][] dp = new int[n+1][2]; for(int i = 1; i <= n; i++){ dp[i][0] = 0; dp[i][1] = 0; } dp[1][0] = a[1]; dp[1][1] = b[1]; for(int i = 2; i < n; i++){ dp[i][1] = Math.max(dp[i-1][0]+c[i],dp[i-1][1]+b[i]); dp[i][0] = Math.max(dp[i-1][0]+b[i],dp[i-1][1]+a[i]); } System.out.println(Math.max(dp[n-1][0]+b[n],dp[n-1][1]+a[n])); } public static boolean isPrime(int n){ if(n == 1) return false; if(n == 2 || n == 3) return true; for(int i = 2; i <= Math.sqrt(n); i++){ if(n % i == 0) return false; } return true; } // tar の方が数字が大きいかどうか static boolean compare(String tar, String src) { if (src == null) return true; if (src.length() == tar.length()) { int len = tar.length(); for (int i = 0; i < len; i++) { if (src.charAt(i) > tar.charAt(i)) { return false; } else if (src.charAt(i) < tar.charAt(i)) { return true; } } return tar.compareTo(src) > 0 ? true : false; } else if (src.length() < tar.length()) { return true; } else if (src.length() > tar.length()) { return false; } return false; } public static class Edge{ int from; int to; Edge(int from, int to){ this.from = from; this.to = to; } } public static void swap(long a, long b){ long tmp = 0; if(a > b){ tmp = a; a = b; b = tmp; } } static class Pair implements Comparable<Pair>{ int first, second; Pair(int a, int b){ first = a; second = b; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Pair)) return false; Pair p = (Pair) o; return first == p.first && second == p.second; } @Override public int compareTo(Pair p){ return first == p.first ? second - p.second : first - p.first; //firstで昇順にソート //return (first == p.first ? second - p.second : first - p.first) * -1; //firstで降順にソート //return second == p.second ? first - p.first : second - p.second;//secondで昇順にソート //return (second == p.second ? first - p.first : second - p.second)*-1;//secondで降順にソート } } //繰り返し二乗法 public static long pow(long x, long n){ long ans = 1; while(n > 0){ if((n & 1) == 1){ ans = ans * x; ans %= mod; } x = x * x % mod; n >>= 1; } return ans; } public static long div(long x, long y){ return (x*pow(y, mod-2))%mod; } //fac, inv, finvテーブルの初期化、これ使う場合はinitComb()で初期化必要 public static void initComb(){ fac[0] = finv[0] = inv[0] = fac[1] = finv[1] = inv[1] = 1; for (int i = 2; i < size; ++i) { fac[i] = fac[i - 1] * i % mod; inv[i] = mod - (mod / i) * inv[(int) (mod % i)] % mod; finv[i] = finv[i - 1] * inv[i] % mod; } } //nCk % mod public static long comb(int n, int k){ return fac[n] * finv[k] % mod * finv[n - k] % mod; } //n! % mod public static long fact(int n){ return fac[n]; } //(n!)^-1 with % mod public static long finv(int n){ return finv[n]; } static class UnionFind { int[] parent; public UnionFind(int size) { parent = new int[size]; Arrays.fill(parent, -1); } public boolean unite(int x, int y) { x = root(x); y = root(y); if (x != y) { if (parent[y] < parent[x]) { int tmp = y; y = x; x = tmp; } parent[x] += parent[y]; parent[y] = x; return true; } return false; } public boolean same(int x, int y) { return root(x) == root(y); } public int root(int x) { return parent[x] < 0 ? x : (parent[x] = root(parent[x])); } public int size(int x) { return -parent[root(x)]; } } public static int upperBound(int[] array, int value) { int low = 0; int high = array.length; int mid; while( low < high ) { mid = ((high - low) >>> 1) + low; // (high + low) / 2 if( array[mid] <= value ) { low = mid + 1; } else { high = mid; } } return low; } public static final int lowerBound(final int[] arr, final int value) { int low = 0; int high = arr.length; int mid; while (low < high){ mid = ((high - low) >>> 1) + low; //(low + high) / 2 (オーバーフロー対策) if (arr[mid] < value) { low = mid + 1; } else { high = mid; } } return low; } //n,mの最大公約数 public static long gcd(long n, long m){ if(m > n) return gcd(m,n); if(m == 0) return n; return gcd(m, n%m); } //3要素のソート private class Pair2 implements Comparable<Pair2> { String s; int p; int index; public Pair2(String s, int p, int index) { this.s = s; this.p = p; this.index = index; } public int compareTo(Pair2 other) { if (s.equals(other.s)) { return other.p - this.p; } return this.s.compareTo(other.s); } } //c -> intに変換 public static int c2i(char c){ if('A' <= c && c <= 'Z'){ return c - 'A'; }else{ return c - 'a' + 26; } } // int -> charに変換 public static char i2c(int i){ if(0 <= i && i < 26){ return (char)(i + 'A'); }else{ return (char)(i + 'a' - 26); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
bea53e481d738d57e6df58f11949d36a
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class D208 { static int N; static long[] a, b, c; static long[][] memo; public static void main(String[] args) { FS scan = new FS(System.in); N = scan.nextInt(); a = new long[N]; b = new long[N]; c = new long[N]; for(int i=0;i<N;i++)a[i] = scan.nextLong(); for(int i=0;i<N;i++)b[i] = scan.nextLong(); for(int i=0;i<N;i++)c[i] = scan.nextLong(); memo = new long[2][N]; for(int i=0;i<2;i++)Arrays.fill(memo[i], -1); System.out.println(solve(0,0)); } private static long solve(int flag, int idx) { if(idx==N)return 0; if(memo[flag][idx]!=-1)return memo[flag][idx]; long sol = 0; if(flag==1){ if(idx!=N-1)sol = c[idx]+solve(0,idx+1); sol = Math.max(sol, b[idx]+solve(1,idx+1)); }else{ if(idx!=N-1)sol = b[idx]+solve(0,idx+1); sol = Math.max(sol, a[idx]+solve(1,idx+1)); } return memo[flag][idx] = sol; } private static class FS { BufferedReader br; StringTokenizer st; public FS(InputStream in) { br = new BufferedReader(new InputStreamReader(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());} } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
b0dae1e0f476d09bc99dfdfd419fb0ac
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class D385 { public static void main(String[] args) { MyScanner in = new MyScanner(); int n = in.nextInt(); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; for(int i=0;i<n;++i){ a[i] = in.nextInt(); } for(int i=0;i<n;++i){ b[i] = in.nextInt(); } for(int i=0;i<n;++i){ c[i] = in.nextInt(); } // 0 -> feed first // 1 -> feed after left // 2 -> feed after right // 3 -> feed after both int[][] dp = new int[n][4]; for (int i = 0; i < n; ++i) { if (i == 0) { dp[i][0] = a[i]; dp[i][1] = a[i]; if (n > 1) { dp[i][2] = b[i]; } } else { dp[i][0] = Math.max(dp[i][0], a[i] + dp[i - 1][2]); dp[i][0] = Math.max(dp[i][0], a[i] + dp[i - 1][3]); dp[i][1] = Math.max(dp[i][1], b[i] + dp[i - 1][0]); dp[i][1] = Math.max(dp[i][1], b[i] + dp[i - 1][1]); if(i < n - 1) { dp[i][2] = Math.max(dp[i][2], b[i] + dp[i - 1][3]); dp[i][2] = Math.max(dp[i][2], b[i] + dp[i - 1][2]); dp[i][3] = Math.max(dp[i][3], c[i] + dp[i - 1][1]); dp[i][3] = Math.max(dp[i][3], c[i] + dp[i - 1][0]); } } } int res = 0; for(int i=0;i<n;++i){ for(int j=0;j<4;++j){ res = Math.max(res, dp[i][j]); } } System.out.println(res); } // -----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } // -------------------------------------------------------- }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
f41bdab50372876df0c0fe5ebc42f5df
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main (String[] args) { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int oo = (int)1e9; int n = fs.nextInt(); int[] a = fs.nextIntArray(n); int[] b = fs.nextIntArray(n); int[] c = fs.nextIntArray(n); if(n == 1) { out.println(a[0]); out.close(); return; } if(n == 2) { out.println(Math.max(a[0] + b[1], a[1] + b[0])); out.close(); return; } c[0] = c[n-1] = -oo; long[][][] dp = new long[n][2][2]; dp[0][0][0] = a[0]; dp[0][0][1] = b[0]; dp[0][1][0] = dp[0][1][1] = -oo; dp[n-1][1][1] = -oo; for(int i = 1; i < n; i++) { long maxC1 = Math.max(dp[i-1][1][1], dp[i-1][0][1]); long maxC2 = Math.max(dp[i-1][1][1], dp[i-1][0][1]); long maxC3 = Math.max(dp[i-1][1][0], dp[i-1][0][0]); long maxC4 = Math.max(dp[i-1][1][0], dp[i-1][0][0]); dp[i][0][0] += maxC1 + a[i]; dp[i][0][1] += maxC2 + b[i]; dp[i][1][0] += maxC3 + b[i]; dp[i][1][1] += maxC4 + c[i]; } long res = Math.max(dp[n-1][0][0], dp[n-1][1][0]); out.println(res); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { try { br = new BufferedReader(new InputStreamReader(System.in)); // br = new BufferedReader(new FileReader("testdata.out")); st = new StringTokenizer(""); } catch (Exception e){e.printStackTrace();} } 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 nextInt() {return Integer.parseInt(next());} public long nextLong() {return Long.parseLong(next());} public double nextDouble() {return Double.parseDouble(next());} public String nextLine() { String line = ""; try {line = br.readLine();} catch (Exception e) {e.printStackTrace();} return line; } public Integer[] nextIntegerArray(int n) { Integer[] a = new Integer[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray(int n) { int[] a = new int[n]; for(int i = 0; i < n; i++) a[i] = nextInt(); return a; } public char[] nextCharArray() { return nextLine().toCharArray(); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
3042ca5156bb9cfd2baa45871ba26f60
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
// Utilities import java.io.*; import java.util.*; public class Main { static int N; static int[] a, b, c; static int[][] dp; // [idx][person before idx full ? 1 : 0] public static void main(String[] args) throws IOException { N = in.iscan(); a = new int[N]; b = new int[N]; c = new int[N]; for (int i = 0; i < N; i++) { a[i] = in.iscan(); } for (int i = 0; i < N; i++) { b[i] = in.iscan(); } for (int i = 0; i < N; i++) { c[i] = in.iscan(); } dp = new int[N][2]; for (int i = 0; i < N; i++) { for (int j = 0; j < 2; j++) { dp[i][j] = -1; } } out.println(attack(0, 0)); out.close(); } static int attack(int idx, int prevFull) { if (idx == N) return 0; if (dp[idx][prevFull] != -1) return dp[idx][prevFull]; int ret = 0; if (prevFull == 1) { ret = b[idx] + attack(idx+1, 1); if (idx != N-1) ret = Math.max(ret, attack(idx+1, 0) + c[idx]); } else { // prevFull == 0 ret = a[idx] + attack(idx+1, 1); if (idx != N-1) ret = Math.max(ret, attack(idx+1, 0) + b[idx]); } return dp[idx][prevFull] = ret; } static INPUT in = new INPUT(System.in); static PrintWriter out = new PrintWriter(System.out); private static class INPUT { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar, numChars; public INPUT (InputStream stream) { this.stream = stream; } public INPUT (String file) throws IOException { this.stream = new FileInputStream (file); } public int cscan () throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read (buf); } if (numChars == -1) return numChars; return buf[curChar++]; } public int iscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } int res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public String sscan () throws IOException { int c = cscan (); while (space (c)) c = cscan (); StringBuilder res = new StringBuilder (); do { res.appendCodePoint (c); c = cscan (); } while (!space (c)); return res.toString (); } public double dscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } double res = 0; while (!space (c) && c != '.') { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); res *= 10; res += c - '0'; c = cscan (); } if (c == '.') { c = cscan (); double m = 1; while (!space (c)) { if (c == 'e' || c == 'E') return res * UTILITIES.fast_pow (10, iscan ()); m /= 10; res += (c - '0') * m; c = cscan (); } } return res * sgn; } public long lscan () throws IOException { int c = cscan (), sgn = 1; while (space (c)) c = cscan (); if (c == '-') { sgn = -1; c = cscan (); } long res = 0; do { res = (res << 1) + (res << 3); res += c - '0'; c = cscan (); } while (!space (c)); return res * sgn; } public boolean space (int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } public static class UTILITIES { static final double EPS = 10e-6; public static int lower_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] >= x) high = mid; else low = mid + 1; } return low; } public static int upper_bound (int[] arr, int x) { int low = 0, high = arr.length, mid = -1; while (low < high) { mid = (low + high) / 2; if (arr[mid] > x) high = mid; else low = mid + 1; } return low; } public static long gcd (long a, long b) { return b == 0 ? a : gcd (b, a % b); } public static long lcm (long a, long b) { return a * b / gcd (a, b); } public static long fast_pow_mod (long b, long x, int mod) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod; return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod; } public static int fast_pow (int b, int x) { if (x == 0) return 1; if (x == 1) return b; if (x % 2 == 0) return fast_pow (b * b, x / 2); return b * fast_pow (b * b, x / 2); } public static long choose (long n, long k) { k = Math.min (k, n - k); long val = 1; for (int i = 0; i < k; ++i) val = val * (n - i) / (i + 1); return val; } public static long permute (int n, int k) { if (n < k) return 0; long val = 1; for (int i = 0; i < k; ++i) val = (val * (n - i)); return val; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
a804197238fd0e773b02bcfaaeb4c528
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* I'm working for the day I will surpass you https://www.a2oj.com/Ladder16.html */ import java.util.*; import java.io.*; import java.math.*; public class x358D2 { static int[] zero; static int[] one; static int[] two; public static void main(String omkar[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); zero = readArr(N, infile, st); one = readArr(N, infile, st); two = readArr(N, infile, st); //I did not read this problem correctly //mask (right then left) int[][] dp = new int[N][2]; for(int i=0; i < N; i++) Arrays.fill(dp[i], -1); int res = dfs(0, 0, dp); System.out.println(res); } public static int dfs(int a, int mask, int[][] dp) { if(a >= dp.length) return 0; if(dp[a][mask] != -1) return dp[a][mask]; int res = 0; if(mask == 0) //left blank { int val = zero[a]+dfs(a+1,1,dp); res = Math.max(res, val); if(a+1 < dp.length) val = dfs(a+1,0,dp)+one[a]; res = Math.max(res, val); } else { int val = one[a]+dfs(a+1,1,dp); res = Math.max(res, val); if(a+1 < dp.length) val = two[a]+dfs(a+1,0,dp); res = Math.max(res, val); } dp[a][mask] = res; return res; } //input shenanigans public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { int[] arr = new int[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); return arr; } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
5249a8af13433c55ae9d05ab33ae9f0f
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.StringTokenizer; /** * Created by Katushka on 08.02.2020. */ public class DimaAndHares { static int[] readArray(int size, InputReader in) { int[] a = new int[size]; for (int i = 0; i < size; i++) { a[i] = in.nextInt(); } return a; } public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); int n = in.nextInt(); int[] a = readArray(n, in); int[] b = readArray(n, in); int[] c = readArray(n, in); long acMet = -1000000; long aMet = a[0]; long nothingMet = b[0]; for (int i = 1; i < n; i++) { long newACMet = Math.max(acMet + b[i], aMet + c[i]); long newAMet = Math.max(Math.max(acMet + a[i], aMet + b[i]), nothingMet + a[i]); long newNothingMet = nothingMet + b[i]; acMet = newACMet; aMet = newAMet; nothingMet = newNothingMet; } out.println(aMet); out.close(); } private 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 String nextString() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
f0874d0196779835bbe0f36e654daf6b
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L * 2 + 7; int[] dx = {-1, 1, 0, 0}; int[] dy = {0, 0, -1, 1}; int n; int[][] dp; int[] a; int[] b; int[] c; void solve() throws IOException { n = nextInt(); a = nextIntArr(n); b = nextIntArr(n); c = nextIntArr(n); dp = new int[1 + n][2]; for (int i = 0; i <= n; i++) { Arrays.fill(dp[i], -1); } int res = rec(0, 0); out(res); } int rec(int cur, int feed) { if (cur == n - 1) { if (feed == 0) { return a[cur]; } else { return b[cur]; } } if (dp[cur][feed] != -1) { return dp[cur][feed]; } int res = 0; if (feed == 0) { res = Math.max(res, rec(cur + 1, 1) + a[cur]); res = Math.max(res, rec(cur + 1, 0) + b[cur]); } else { res = Math.max(res, rec(cur + 1, 1) + b[cur]); res = Math.max(res, rec(cur + 1, 0) + c[cur]); } dp[cur][feed] = res; return res; } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } int gcd(int a, int b) { while(a != 0 && b != 0) { int c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
e3e238c3dcd945edef5fe361884df0ef
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); int[] a = new int[n]; int[] b = new int[n]; int[] c = new int[n]; StringTokenizer s1 = new StringTokenizer(reader.readLine()); StringTokenizer s2 = new StringTokenizer(reader.readLine()); StringTokenizer s3 = new StringTokenizer(reader.readLine()); int[] sum = new int[n]; for (int i=0; i<n; i++) { a[i] = Integer.parseInt(s1.nextToken()); b[i] = Integer.parseInt(s2.nextToken()); c[i] = Integer.parseInt(s3.nextToken()); sum[i] = b[i]; if (i>0) sum[i]+=sum[i-1]; } int[] res = new int[n]; res[0] = a[0]; int result = a[0] + sum[n-1] - sum[0]; for (int i=1; i<n; i++) { int x = 0; int diff = Integer.MIN_VALUE; for (int j=i-1; j>0; j--) { x+=b[j]; diff = Math.max(diff, c[j] - b[j]); res[i] = Math.max(res[i], res[j-1] + x + diff); } x+=b[0]; res[i] = Math.max(res[i], x); res[i]+=a[i]; result = Math.max(result, res[i] + sum[n-1] - sum[i]); } System.out.println(result); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
a9326281ea239f4cd6b0059aa62b16c7
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class D358 { int[][] dp, a; void solve(){ int n = readInt(); a = new int[3][n]; for(int i = 0;i<3;i++){ for(int j = 0;j<n;j++){ a[i][j] = readInt(); } } dp = new int[2][n]; dp[0][n - 1] = a[0][n - 1]; dp[1][n - 1] = a[1][n - 1]; for(int i = n - 2;i>=0;i--){ dp[0][i] = Math.max(a[0][i] + dp[1][i + 1], a[1][i] + dp[0][i + 1]); dp[1][i] = Math.max(a[2][i] + dp[0][i + 1], a[1][i] + dp[1][i + 1]); } out.print(dp[0][0]); } public static void main(String[] args) { new D358().run(); } void run(){ init(); solve(); out.close(); } BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init(){ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } String readLine(){ try{ return in.readLine(); }catch(Exception ex){ throw new RuntimeException(ex); } } String readString(){ while(!tok.hasMoreTokens()){ String nextLine = readLine(); if(nextLine == null) return null; tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt(){ return Integer.parseInt(readString()); } long readLong(){ return Long.parseLong(readString()); } double readDouble(){ return Double.parseDouble(readString()); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
d69046cb779c652b8b0c688e0b91e3c8
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } /////////////////////////////////////////////////////////////////////////////////////////// // RRRRRRRRR AAA HHH HHH IIIIIIIIIIIII LLL // // RR RRR AAAAA HHH HHH IIIIIIIIIII LLL // // RR RRR AAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHHHHHHHHHH III LLL // // RRRRRR AAA AAA HHHHHHHHHHH III LLL // // RR RRR AAAAAAAAAAAAA HHH HHH III LLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIII LLLLLLLLLLLL // // RR RRR AAA AAA HHH HHH IIIIIIIIIIIII LLLLLLLLLLLL // /////////////////////////////////////////////////////////////////////////////////////////// static int n,arr[],brr[],crr[],cache[][]; public static int dp(int pos,int prev) { if(pos==n-1) { if(prev==0) return arr[n-1]; return brr[n-1]; } if(cache[pos][prev]!=-1)return cache[pos][prev]; if(prev==0) return cache[pos][prev]=Math.max(arr[pos]+dp(pos+1,1),brr[pos]+dp(pos+1,0)); else return cache[pos][prev]=Math.max(brr[pos]+dp(pos+1,1),crr[pos]+dp(pos+1,0)); } public static void main(String[] args)throws IOException { Reader sc=new Reader(); PrintWriter out = new PrintWriter(System.out); n=sc.i();arr=sc.arr(n);brr=sc.arr(n);crr=sc.arr(n); cache=new int[n][2]; for(int i=0;i<n;i++)Arrays.fill(cache[i],-1); out.println(dp(0,0)); out.flush(); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
0a4ed760a6ecac7431e0c92e56455740
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { static int n,m; // static ArrayList<Integer>[] graph,tree; public static void main(String[] args)throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(in)); //Scanner sc = new Scanner(System.in); String[] buf = reader.readLine().split(" "); n = Integer.parseInt(buf[0]); int[] none = new int[n], one = new int[n], two = new int[n]; buf = reader.readLine().split(" "); for(int i=0;i<n;i++) none[i] = Integer.parseInt(buf[i]); buf = reader.readLine().split(" "); for(int i=0;i<n;i++) one[i] = Integer.parseInt(buf[i]); buf = reader.readLine().split(" "); for(int i=0;i<n;i++) two[i] = Integer.parseInt(buf[i]); long ans = help(none,one,two,n); System.out.println(ans); } static long help(int[] none, int[] one, int[] two, int n){ if(n==1) return none[0]; if(n==2) return Math.max(none[0]+one[1],one[0]+none[1]); long[] dp1 = new long[n], dp2 = new long[n]; // dp1[i]: the i-th was feed last. dp2[i]: the i-th was feed before i-1 -th dp1[1] = none[0]+one[1]; dp2[1] = one[0]+none[1]; dp1[0] = none[0]; for(int i=2;i<n;i++){ dp1[i] = Math.max(dp1[i-1],dp2[i-1])+one[i]; dp2[i] = none[i]+Math.max(dp1[i-1]-one[i-1]+two[i-1],dp2[i-1]-none[i-1]+one[i-1]); } return Math.max(dp1[n-1],dp2[n-1]); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
15eebfd52dcc98ecdcd11a8eed1322ae
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class D358 { public static void main(String[] args) throws IOException { BufferedReader inp = new BufferedReader(new InputStreamReader(System.in)); int size = Integer.parseInt(inp.readLine()); int[] a = new int[size]; int[] b = new int[size]; int[] c = new int[size]; String[] s1 = inp.readLine().split(" "); String[] s2 = inp.readLine().split(" "); String[] s3 = inp.readLine().split(" "); for(int i=0;i<size;i++){ a[i] = Integer.parseInt(s1[i]); b[i] = Integer.parseInt(s2[i]); c[i] = Integer.parseInt(s3[i]); } c[0] = 0; c[size-1] = 0; solve(a,b,c); } static void solve(int[] a,int[] b,int[] c){ int[] dp0 = new int[a.length+1]; int[] dp1 = new int[a.length+1]; dp0[a.length-1] = a[a.length-1]; dp1[a.length-1] = b[a.length-1]; for(int i=a.length-2;i>=0;i--){ dp0[i] = Math.max(dp0[i+1]+b[i],dp1[i+1]+a[i]); dp1[i] = Math.max(dp0[i+1]+c[i],dp1[i+1]+b[i]); } System.out.println(dp0[0]); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
94d930b132b8578ea24800248e7f64fd
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class Abood2C { static int n, a[], b[], c[]; static int memo[][]; static int solve(int i, int l) { if(i == n - 1) if(l == 0) return b[i]; else return a[i]; if(memo[i][l] != -1) return memo[i][l]; int ans = 0; if(l == 0) { ans = b[i] + solve(i + 1, 0); ans = Math.max(ans, c[i] + solve(i + 1, 1)); } else { ans = a[i] + solve(i + 1, 0); ans = Math.max(ans, b[i] + solve(i + 1, 1)); } return memo[i][l] = ans; } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); n = sc.nextInt(); a = new int[n]; b = new int[n]; c = new int[n]; for (int i = 0; i < n; i++) a[i] = sc.nextInt(); for (int i = 0; i < n; i++) b[i] = sc.nextInt(); for (int i = 0; i < n; i++) c[i] = sc.nextInt(); memo = new int[n][2]; for (int i = 0; i < n; i++) Arrays.fill(memo[i], -1); out.println(solve(0, 1)); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if(x.charAt(0) == '-') { neg = true; start++; } for(int i = start; i < x.length(); i++) if(x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if(dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg?-1:1); } public boolean ready() throws IOException {return br.ready();} } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
829fd80bbf4863df71b33f601cbed46d
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable { static class pair implements Comparable { int f,s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(f>pr.f) return 1; else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,s; int t; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff,ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(f>tr.f) return 1; else if(f==tr.f) { if(s>tr.s) return -1; else return 1; } else return -1; } } int n; int a[],b[],c[]; int memo[][]; int solve(int i,int k) { if(i==n) { if(k==0) return a[i]; if(k==1) return b[i]; } if(memo[i][k]!=-1) return memo[i][k]; if(k==0) { memo[i][k]=Math.max(a[i]+solve(i+1,1),b[i]+solve(i+1,0)); } if(k==1) { memo[i][k]=Math.max(b[i]+solve(i+1,1),c[i]+solve(i+1,0)); } return memo[i][k]; } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); n=in.ni(); a=new int[n+1]; b=new int[n+1]; c=new int[n+1]; for(int i=1;i<=n;i++) a[i]=in.ni(); for(int i=1;i<=n;i++) b[i]=in.ni(); for(int i=1;i<=n;i++) c[i]=in.ni(); memo=new int[n+1][2]; for(int i=1;i<=n;i++) Arrays.fill(memo[i],-1); out.println(solve(1,0)); out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
db9f3ed9b7a5fa2099532b323555a5bb
train_002.jsonl
1382715000
Dima liked the present he got from Inna very much. He liked the present he got from Seryozha even more. Dima felt so grateful to Inna about the present that he decided to buy her n hares. Inna was very happy. She lined up the hares in a row, numbered them from 1 to n from left to right and started feeding them with carrots. Inna was determined to feed each hare exactly once. But in what order should she feed them?Inna noticed that each hare radiates joy when she feeds it. And the joy of the specific hare depends on whether Inna fed its adjacent hares before feeding it. Inna knows how much joy a hare radiates if it eats when either both of his adjacent hares are hungry, or one of the adjacent hares is full (that is, has been fed), or both of the adjacent hares are full. Please note that hares number 1 and n don't have a left and a right-adjacent hare correspondingly, so they can never have two full adjacent hares.Help Inna maximize the total joy the hares radiate. :)
256 megabytes
//package que_b; import java.io.*; import java.util.*; import java.math.*; public class utkarsh { InputStream is; PrintWriter out; long mod = (long) (1e9 + 7), inf = (long) (3e18); boolean SHOW_TIME, debug; void solve() { //Enter code here utkarsh //SHOW_TIME = true; //debug = true; int n = ni(); int a[] = na(n); int b[] = na(n); int c[] = na(n); long dp[][] = new long[2][n]; dp[0][0] = a[0]; dp[1][0] = b[0]; for(int i = 1; i < n; i++) { dp[0][i] = Math.max(dp[1][i-1] + a[i], dp[0][i-1] + b[i]); // taking before i+1 dp[1][i] = Math.max(dp[1][i-1] + b[i], dp[0][i-1] + c[i]); // taking after i+1 } out.println(dp[0][n-1]); } //---------- I/O Template ---------- public static void main(String[] args) { new utkarsh().run(); } void run() { is = System.in; out = new PrintWriter(System.out); long start = System.currentTimeMillis(); solve(); long end = System.currentTimeMillis(); if(SHOW_TIME) out.println("\n" + (end - start) + " ms"); out.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] na(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } }
Java
["4\n1 2 3 4\n4 3 2 1\n0 1 1 0", "7\n8 5 7 6 1 8 9\n2 7 9 5 4 3 1\n2 3 3 4 1 1 3", "3\n1 1 1\n1 2 1\n1 1 1"]
2 seconds
["13", "44", "4"]
null
Java 8
standard input
[ "dp", "greedy" ]
99cf10673cb275ad3b90bcd3757ecd47
The first line of the input contains integer n (1 ≤ n ≤ 3000) — the number of hares. Then three lines follow, each line has n integers. The first line contains integers a1 a2 ... an. The second line contains b1, b2, ..., bn. The third line contains c1, c2, ..., cn. The following limits are fulfilled: 0 ≤ ai, bi, ci ≤ 105. Number ai in the first line shows the joy that hare number i gets if his adjacent hares are both hungry. Number bi in the second line shows the joy that hare number i radiates if he has exactly one full adjacent hare. Number сi in the third line shows the joy that hare number i radiates if both his adjacent hares are full.
1,800
In a single line, print the maximum possible total joy of the hares Inna can get by feeding them.
standard output
PASSED
34a98fc7cd741ebca1fc972c65fa8411
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.Scanner; public class Ishu { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n,i,min=0,max=0,mi=0,Mi=0; int[] a=new int[1000]; n=scan.nextInt(); for(i=0;i<n;++i) { a[i]=scan.nextInt(); if(i==0) { min=max=a[i]; mi=Mi=i+1; } else if(a[i]<min) { min=a[i]; mi=i+1; } else if(a[i]>max) { max=a[i]; Mi=i+1; } } if(min==max) System.out.println("Exemplary pages."); else { int nomin=0,nomax=0; for(i=0;i<n;++i) { if(a[i]==min) ++nomin; else if(a[i]==max) ++nomax; } if(nomin>1||nomax>1) System.out.println("Unrecoverable configuration."); else { if(n<=2) { if((((float)(max-min))/2)-((max-min)/2)==0.0f) System.out.println(((max-min)/2)+" ml. from cup #"+mi+" to cup #"+Mi+"."); else System.out.println("Unrecoverable configuration."); } else { int simple=0,min1=0,max1=0,x=0; for(i=0;i<n;++i) if(!(a[i]==min||a[i]==max)) { simple=a[i]; if(x==0) { max1=min1=simple; ++x; } else { if(simple<min1) min1=simple; else if(simple>max1) max1=simple; } } if(min1==max1) { if((max-simple)==(simple-min)) System.out.println(((max-min)/2)+" ml. from cup #"+mi+" to cup #"+Mi+"."); else System.out.println("Unrecoverable configuration."); } else System.out.println("Unrecoverable configuration."); } } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
a08200202cd7dd50ac935e2b365f3c1c
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.*; public class Main{ public static void main(String [] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int x[] = new int[n]; int sum=0; for(int i=0 ;i<n ;i++) { x[i]= scan.nextInt(); sum += x[i]; } int a=0; int b=0; int count=0; float norm = ((float)sum)/n; for(int i=0 ; i<n && count < 3 ; i++) { if(x[i]<norm) { count++; a = i+1; } else if(x[i] > norm) { count++; b=i+1; } } if(count==3 || norm!=(int)norm ) { System.out.println("Unrecoverable configuration."); } else if (a==0) { System.out.println("Exemplary pages."); } else { System.out.println((int)(x[b-1]-norm)+" ml. from cup #"+a+" to cup #"+b+"."); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
4e44f3127e82c84f72c42e2451bb0269
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; import java.util.stream.*; @SuppressWarnings("unchecked") public class P99B { class Cup implements Comparable<Cup> { int n, v; public Cup(int n, int v) { this.n = n; this.v = v; } @Override public int compareTo(Cup c) { return (v - c.v); } @Override public String toString() { return ("cup #" + n); } } public void run() throws Exception { int n = nextInt(); TreeMap<Cup, Integer> cups = new TreeMap(); for (int i = 1; i <= n; i++) { Cup cup = new Cup(i, nextInt()); cups.put(cup, cups.getOrDefault(cup, 0) + 1); } if (cups.size() == 1) { println("Exemplary pages."); } else if (n == 2) { if (((cups.firstKey().v + cups.lastKey().v) % 2) == 1) { println("Unrecoverable configuration."); } else { println(((cups.lastKey().v - cups.firstKey().v) / 2) + " ml. from " + cups.firstKey() + " to " + cups.lastKey() + "."); } } else if (cups.size() != 3) { println("Unrecoverable configuration."); } else { if ((cups.firstEntry().getValue() != 1) || (cups.lastEntry().getValue() != 1)) { println("Unrecoverable configuration."); } else { Cup f = cups.pollFirstEntry().getKey(); Cup m = cups.pollFirstEntry().getKey(); Cup l = cups.pollFirstEntry().getKey(); if ((f.v + l.v) != (2 * m.v)) { println("Unrecoverable configuration."); } else { println(((l.v - f.v) / 2) + " ml. from " + f + " to " + l + "."); } } } } public static void main(String... args) throws Exception { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedOutputStream(System.out)); new P99B().run(); br.close(); pw.close(); System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]"); } static long startTime = System.currentTimeMillis(); static BufferedReader br; static PrintWriter pw; StringTokenizer stok; String nextToken() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } void print(byte b) { print("" + b); } void print(int i) { print("" + i); } void print(long l) { print("" + l); } void print(double d) { print("" + d); } void print(char c) { print("" + c); } void print(Object o) { if (o instanceof int[]) { print(Arrays.toString((int [])o)); } else if (o instanceof long[]) { print(Arrays.toString((long [])o)); } else if (o instanceof char[]) { print(Arrays.toString((char [])o)); } else if (o instanceof byte[]) { print(Arrays.toString((byte [])o)); } else if (o instanceof short[]) { print(Arrays.toString((short [])o)); } else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o)); } else if (o instanceof float[]) { print(Arrays.toString((float [])o)); } else if (o instanceof double[]) { print(Arrays.toString((double [])o)); } else if (o instanceof Object[]) { print(Arrays.toString((Object [])o)); } else { print("" + o); } } void print(String s) { pw.print(s); } void println() { println(""); } void println(byte b) { println("" + b); } void println(int i) { println("" + i); } void println(long l) { println("" + l); } void println(double d) { println("" + d); } void println(char c) { println("" + c); } void println(Object o) { print(o); println(); } void println(String s) { pw.println(s); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } char nextChar() throws IOException { return (char) (br.read()); } String next() throws IOException { return nextToken(); } String nextLine() throws IOException { return br.readLine(); } int [] readInt(int size) throws IOException { int [] array = new int [size]; for (int i = 0; i < size; i++) { array[i] = nextInt(); } return array; } long [] readLong(int size) throws IOException { long [] array = new long [size]; for (int i = 0; i < size; i++) { array[i] = nextLong(); } return array; } double [] readDouble(int size) throws IOException { double [] array = new double [size]; for (int i = 0; i < size; i++) { array[i] = nextDouble(); } return array; } String [] readLines(int size) throws IOException { String [] array = new String [size]; for (int i = 0; i < size; i++) { array[i] = nextLine(); } return array; } int gcd(int a, int b) { return ((b > 0) ? gcd(b, a % b) : a); } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
d5f5f145d5bfe70043e5a050af3c7462
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.StringTokenizer; import java.util.Set; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author neuivn */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); Set<Integer> hs = new HashSet<Integer>(); int[] arr = new int[N]; int[] cnt = new int[10001]; int max = -1; int maxId = -1; int min = Integer.MAX_VALUE; int minId = -1; for (int i = 0; i < N; ++i) { arr[i] = in.nextInt(); cnt[arr[i]]++; hs.add(arr[i]); } if (hs.size() == 1) { out.println("Exemplary pages."); } else { for (int i = 0; i < N; ++i) { if (cnt[arr[i]] == 1) { if (max < arr[i]) { max = arr[i]; maxId = i; } if (min > arr[i]) { min = arr[i]; minId = i; } } } if (maxId == minId || ((arr[maxId] + arr[minId]) % 2 != 0)) { out.println("Unrecoverable configuration."); } else { String res = ((arr[maxId] - (arr[maxId] + arr[minId]) / 2)) + " ml. from cup #" + (minId + 1) + " to cup #" + (maxId + 1) + "."; arr[maxId] = ((max + min) / 2); arr[minId] = ((max + min) / 2); boolean check = true; for (int j = 0; j < N - 1; ++j) { check &= (arr[j] == arr[j + 1]); } if (!check) out.println("Unrecoverable configuration."); else out.println(res); } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
13a5c87d58cd20eaf1827d0cec32204d
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.List; import java.util.Scanner; import java.util.ArrayList; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Mouna Cheikhna */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } int sum = 0; for (int x : a) sum += x; if (sum % n != 0) { out.println("Unrecoverable configuration."); return; } int avg = sum / n; List<Integer> indexes = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a[i] != avg) indexes.add(i); } if (indexes.size() == 0) { out.println("Exemplary pages."); return; } if (indexes.size() != 2) { out.println("Unrecoverable configuration."); return; } int first = indexes.get(0); int second = indexes.get(1); if (a[first] > a[second]) { int t = first; first = second; second = t; } out.println((-a[first] + avg) + " ml. from cup #" + (first + 1) + " to cup #" + (second + 1) + "."); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
68201892442a6c3834cc15eb3c9693d3
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import javax.print.attribute.HashDocAttributeSet; import java.io.*; import java.util.*; public class Main{ public static void main(String[] args) { MyScanner scanner = new MyScanner(); int n = scanner.nextInt(), x = 0, y = 0, other = 0; HashMap<Integer, Integer> maps = new HashMap<Integer, Integer>(); HashMap<Integer, Integer> last = new HashMap<Integer, Integer>(); boolean recor = false; for( int i = 0; i < n ; i++ ) { int val = scanner.nextInt(); last.put( val , i ); if( maps.containsKey( val ) ){ maps.put( val, maps.get(val) + 1 ); } else { maps.put( val, 1 ); } } if( maps.size() == 1 ) { System.out.println( "Exemplary pages." ); return; } else if( maps.size() == 3 || n == 2 ) { ArrayList<Integer> single = new ArrayList<Integer>(); other = -1; for( Integer key : maps.keySet() ) { if( maps.get(key) == 1 ) { single.add( key ); } else { other = key; } } if( single.size() == 3 && n == 3 ) { Collections.sort(single); x = single.get(0); y = single.get(2); other = single.get(1); if( ( x + y == 2 * other || n == 2 ) && Math.abs( x - y ) % 2 == 0 ) { recor = true; } } if( single.size() == 2 ) { x = single.get(0); y = single.get(1); if( ( x + y == 2 * other || n == 2 ) && Math.abs( x - y ) % 2 == 0 ) { if( x > y ) { int t = y; y = x; x = t; } recor = true; } } } if( recor ) { System.out.println( (( y - x ) / 2) +" ml. from cup #"+ ( last.get(x) + 1 ) + " to cup #" + ( last.get(y) + 1 ) + "." ); } else { System.out.println( "Unrecoverable configuration." ); } } } class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } public int mod(long x) { // TODO Auto-generated method stub return (int) x % 1000000007; } public int mod(int x) { return x % 1000000007; } boolean hasNext() { if (st.hasMoreElements()) return true; try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.hasMoreTokens(); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int[] readIntArray( int n ) { int ar[] = new int[ n ]; for( int i = 0; i < n ; i++ ) ar[ i ] = this.nextInt(); return ar; } public long nextLong() { return Long.parseLong(next()); } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
0d765f8a8839f2eb3673381bd25019d2
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.IOException; import java.util.Arrays; import java.util.Comparator; import java.util.InputMismatchException; /** * Created by jizhe on 2016/1/8. */ public class HelpChefGerasim { public static class FasterScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = System.in.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public String nextString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int nextInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } public long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } private static class Node implements Comparable<Node> { private int index, volume; public Node(int index, int volume) { this.index = index; this.volume = volume; } public int compareTo(Node another) { return Integer.compare(this.volume, another.volume); } } public static void main(String[] args) { //Scanner in = new Scanner(new BufferedInputStream(System.in)); FasterScanner in = new FasterScanner(); int N = in.nextInt(); Node[] cups = new Node[N]; for( int i = 0; i < N; i++ ) { cups[i] = new Node(i+1, in.nextInt()); } Arrays.sort(cups); if( cups[0].volume == cups[N-1].volume ) { System.out.printf("Exemplary pages.\n"); return; } int prev = cups[0].volume; int distinctness = 1; for( int i = 1; i < N; i++ ) { if( cups[i].volume != prev ) { distinctness++; } prev = cups[i].volume; } if( distinctness > 3 ) { System.out.printf("Unrecoverable configuration.\n"); } else if( distinctness == 2 ) { if( N != 2 ) { System.out.printf("Unrecoverable configuration.\n"); } else { int from = cups[0].index, to = cups[1].index; int diff = cups[0].volume+cups[1].volume; if( diff%2 == 1 ) { System.out.printf("Unrecoverable configuration.\n"); } else { int pour = diff/2-cups[0].volume; System.out.printf("%d ml. from cup #%d to cup #%d.\n", pour, from, to); } } } else { int from = cups[0].index, to = cups[N-1].index; int diff = cups[0].volume+cups[N-1].volume; if( diff%2 == 1 ) { System.out.printf("Unrecoverable configuration.\n"); } else { int pour = diff/2-cups[0].volume; if( pour+cups[0].volume != cups[1].volume || pour+cups[0].volume != cups[N-2].volume ) { System.out.printf("Unrecoverable configuration.\n"); } else { System.out.printf("%d ml. from cup #%d to cup #%d.\n", pour, from, to); } } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
8e83921557d2dd0006914b8ad022fb82
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class P99B { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } static class Task { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int[] a = new int[n]; long sum = 0; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); sum += a[i]; } if (sum % n != 0) { out.println("Unrecoverable configuration."); return; } int av = (int) (sum / n); int[] d = new int[n]; boolean allsame = true; int pourings = 0; Map<Integer, Integer> deltas = new HashMap<>(); for (int i = 0; i < n; i++) { d[i] = a[i] - av; if (d[i] != 0) { allsame = false; pourings++; deltas.put(d[i], i); } } if (allsame) { out.println("Exemplary pages."); return; } if (pourings <= 2) { for (int x : deltas.keySet()) { if (deltas.containsKey(-x)) { out.println(Math.abs(x) + " ml. from cup #" + (deltas.get(-Math.abs(x)) + 1) + " to cup #" + (1 + deltas.get(Math.abs(x))) + "."); return; } } } out.println("Unrecoverable configuration."); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
877e712deaff7a3bde544e4ae5aad572
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.*; public class Main { public static void main(String arg[]) { Scanner sc = new Scanner(System.in); int n = Integer.parseInt(sc.next()); List<Integer> list = new ArrayList<>(); for(int i = 0; i < n; ++i){ list.add(Integer.parseInt(sc.next())); } long sum = list.stream().mapToLong(i -> i).sum(); long average = sum / list.size(); long count = list.stream().filter(i -> i != average).count(); if(count == 0){ System.out.println("Exemplary pages."); return; }else if(count != 2){ System.out.println("Unrecoverable configuration."); return; } int index1 = -1, index2 = -1; for(int i = 0; i < list.size(); ++i){ if(list.get(i) != average){ if(index1 == -1){ index1 = i; }else{ index2 = i; } } } if(list.get(index1) + list.get(index2) != average * 2){ System.out.println("Unrecoverable configuration."); }else{ if(list.get(index1) > list.get(index2)){ System.out.println(String.format("%d ml. from cup #%d to cup #%d.", (list.get(index1) - list.get(index2)) / 2, index2 + 1, index1 + 1)); }else { System.out.println(String.format("%d ml. from cup #%d to cup #%d.", (list.get(index2) - list.get(index1)) / 2, index1 + 1, index2 + 1)); } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
18e060929b46b8b27c75df7778f6a0a7
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Scanner; public class b78 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); HashMap<Integer,Integer> cups = new HashMap<Integer,Integer>(); ArrayList<Integer> actual = new ArrayList<Integer>(); for(int i = 0; i < n; i++){ int amount = in.nextInt(); actual.add(amount); if(!cups.containsKey(amount)){ cups.put(amount, 0); } cups.put(amount, cups.get(amount)+1); } //System.out.println(cups); if(cups.size()>3){ System.out.println("Unrecoverable configuration."); return; } if(cups.size()==1){ System.out.println("Exemplary pages."); return; } boolean foundnonone = false; ArrayList<Integer> sorted = new ArrayList<Integer>(); for(Integer i : cups.keySet()){ sorted.add(i); if(cups.get(i)>1){ if(foundnonone){ System.out.println("Unrecoverable configuration."); return; }else{ foundnonone=true; } } } Collections.sort(sorted); int higher = sorted.get(sorted.size()-1); int lower = sorted.get(0); int amount =0 ; if((higher-lower)%2!=0){ System.out.println("Unrecoverable configuration."); return; }else{ amount = (higher-lower)/2; } int higherloc = -1; int lowerloc = -1; for(int i = 0; i < actual.size(); i++){ if(actual.get(i)==higher){ if(higherloc!=-1){ System.out.println("Unrecoverable configuration."); return; } higherloc=i+1; } if(actual.get(i)==lower){ if(lowerloc!=-1){ System.out.println("Unrecoverable configuration."); return; } lowerloc = i+1; } } if(lowerloc==-1||higherloc==-1){ System.out.println("Unrecoverable configuration."); return; } if(sorted.size()>2){ if(higher-amount!=sorted.get(1)||lower+amount!=sorted.get(1)){ System.out.println("Unrecoverable configuration."); return; } } System.out.println(amount+" ml. from cup #"+lowerloc+" to cup #"+higherloc+"."); } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
b63ad31062e1d2f28244cc22982a9be2
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import static java.lang.Math.*; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.Double.parseDouble; import static java.lang.String.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); //(new FileReader("input.in")); StringBuilder out = new StringBuilder(); StringTokenizer tk; //PrintWriter pw = new PrintWriter("output.out", "UTF-8"); int n = parseInt(in.readLine()); int [] ml = new int[n]; int sum = 0; for(int i=0; i<n; i++) { ml[i] = parseInt(in.readLine()); sum += ml[i]; } if(sum%n != 0) System.out.println("Unrecoverable configuration."); else { int req = sum/n; int c1=-1,c2=-1; for(int i=0; i<n; i++) { if(ml[i] != req) { if(c1==-1) c1 = i; else if(c2==-1) c2 = i; else { c1 = c2 = -2; break; } } } if(c1==-1 && c2==-1) System.out.println("Exemplary pages."); else if(c1==-2 && c2==-2) System.out.println("Unrecoverable configuration."); else { if(abs(ml[c2]-ml[c1])/2+min(ml[c1],ml[c2]) == req) System.out.printf("%d ml. from cup #%d to cup #%d.\n", abs(req-ml[c2]), (ml[c1]<ml[c2] ? c1+1 : c2+1), (ml[c1]>ml[c2] ? c1+1 : c2+1)); else System.out.println("Unrecoverable configuration."); } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
e2b81e5d8df9507d3d3679e232f679a1
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.*; import java.io.*; public class b { public static void main(String[] arg) throws IOException { new b(); } public b() throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); int[] vs = new int[n]; for(int i = 0; i < n; i++) vs[i] = in.nextInt(); boolean f = true; for(int i = 1; i < n; i++) { if(vs[i] != vs[i-1]) f = false; } if(f) { out.println("Exemplary pages."); } else { f = true; loop: for(int k = 0; k <= 10000; k++) { if(possible(vs, k)) { for(int i = 0; i < n; i++) { for(int j = i+1; j < n; j++) { if(vs[i] != k && vs[j] != k) { if(vs[i] > vs[j]) { out.printf("%d ml. from cup #%d to cup #%d.\n", (vs[i]-vs[j])/2, j+1, i+1); } else { out.printf("%d ml. from cup #%d to cup #%d.\n", (vs[j]-vs[i])/2, i+1, j+1); } f = false; break loop; } } } } } if(f) { out.println("Unrecoverable configuration."); } } in.close(); out.close(); } boolean possible(int[] vs, int k) { int cnt = 0; int left = 0; for(int i = 0; i < vs.length; i++) { if(vs[i] != k) { left += k-vs[i]; cnt++; } } return cnt == 2 && left == 0; } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = new StringTokenizer(""); } String next() throws IOException { while(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } void close() throws IOException { br.close(); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
bc0cfa30adfe4ba57a19aa00ca23b66a
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.*; import java.io.*; public class Help_Chef_Gerasim { public static void main(String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); int a[]=new int[n],b[]=new int[n]; for(int i=0; i<n; i++) { a[i]=Integer.parseInt(br.readLine()); b[i]=a[i]; } Arrays.sort(a); if(a[0]==a[n-1]) System.out.println("Exemplary pages."); else { int p1=0,p2=0; int d=(a[n-1]-a[0])/2; for(int i=0; i<n; i++) { if(b[i]==a[0]) { b[i]+=d; p1=i+1; break; } } for(int i=0; i<n; i++) { if(b[i]==a[n-1]) { b[i]-=d; p2=i+1; break; } } boolean ok=true; for(int i=1; i<n; i++) { if(b[i]!=b[i-1]) {ok=false;break;} } System.out.println(!ok?"Unrecoverable configuration.":d+" ml. from cup #"+p1+" to cup #"+p2+"."); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
4096ee0428502d3873b9657d65f5c0c9
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; import java.io.IOException; import java.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); ChefGerasim solver = new ChefGerasim(); solver.solve(1, in, out); out.close(); } static class ChefGerasim { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); ChefGerasim.Entry arr[] = new ChefGerasim.Entry[n]; long sum = 0; for (int i = 0; i < n; i++) { arr[i] = new ChefGerasim.Entry(i + 1, in.nextLong()); sum += arr[i].val; } double div = (double) sum / (double) n; if (div != Math.floor(div)) { out.println("Unrecoverable configuration."); return; } long d = (long) div; long count = 0; for (int i = 0; i < n; i++) { if (arr[i].val == d) { count++; } } Arrays.sort(arr); if (count == n) { out.println("Exemplary pages."); } else if (count == n - 2 && ((arr[0].val + arr[n - 1].val) / 2) == d) { out.println((d - arr[0].val) + " ml. " + "from cup #" + arr[0].pos + " to cup" + " #" + arr[n - 1].pos + "."); } else { out.println("Unrecoverable configuration."); } } static class Entry implements Comparable<ChefGerasim.Entry> { int pos; long val; public Entry(int pos, long val) { this.pos = pos; this.val = val; } public int compareTo(ChefGerasim.Entry entry) { return (int) (this.val - entry.val); } } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
190f6740a09266c97600ac6451511218
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.util.*; public class Main { public static void ans(int []arr,int sum,int n){ if(sum%n!=0){ System.out.println("Unrecoverable configuration."); return; } int equal=sum/n; int inc=0,dec=0; for(int i=0;i<n;i++){ if(arr[i]>equal) inc++; else if(arr[i]<equal) dec++; } if (inc==0 && dec==0){ System.out.println("Exemplary pages."); return; } else if(inc==1 && dec==1){ int a=0,b=0,ia=0,ib=0; for(int i=0;i<n;i++){ if(arr[i]>equal){ a=arr[i]-equal; ia=i; } else if(arr[i]<equal){ b=equal-arr[i]; ib=i; } } if(a==b){ System.out.println(a+" ml. from cup #"+(ib+1)+" to cup #"+(ia+1)+"."); return; }else{ System.out.println("Unrecoverable configuration."); return; } }else{ System.out.println("Unrecoverable configuration."); return; } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()); int arr[]=new int[n]; int sum=0; for(int i=0;i<n;i++){ arr[i]=Integer.parseInt(br.readLine()); sum=sum+arr[i]; } ans(arr,sum,n); }}
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
a5baf27a11d1b60d0bfffba3932951c6
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; public class Main{ public static void main(String[]args)throws IOException{ PrintWriter pw=new PrintWriter(System.out,true); BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(bf.readLine()); int[]a=new int[n]; ArrayList<Integer>b=new ArrayList<Integer>(); int max=0,min=10000; for(int i=0;i<n;i++){ a[i]=Integer.parseInt(bf.readLine()); if(!b.contains(a[i])) b.add(a[i]); if(a[i]<min) min=a[i]; if(a[i]>max) max=a[i]; } int x=0; for(int i=0;i<b.size();i++){ if(b.get(i)!=min && b.get(i)!=max) x=b.get(i); } if(b.size()==1) System.out.println("Exemplary pages."); else if(b.size()>3 || (b.size()==3 && max-x!=x-min)) System.out.println("Unrecoverable configuration."); else{ int minc=0,maxc=0,minp=0,maxp=0;; for(int i=0;i<a.length;i++){ if(a[i]==min){ minc++; minp=i+1; } if(a[i]==max){ maxc++; maxp=i+1; } } if(b.size()==3){ if(minc==1 && maxc==1) System.out.println((max-x)+" ml. from cup #"+minp+" to cup #"+maxp+"."); else System.out.println("Unrecoverable configuration."); } else{ int d=max-min; if(a.length==2 && d%2==0) System.out.println(d/2+" ml. from cup #"+minp+" to cup #"+maxp+"."); else System.out.println("Unrecoverable configuration."); } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
e2e54934a61f0395ea21151058458073
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.*; import java.io.*; public class Main implements Runnable { public void solve() throws IOException { int N = nextInt(); int[] milk = new int[N]; for(int i = 0; i < N; i++) milk[i] = nextInt(); int sum = 0; for(int i = 0; i < N; i++) sum += milk[i]; if(sum % N != 0){ out.println("Unrecoverable configuration."); return; } int avg = sum / N; int poured = 0; for(int i = 0; i < N; i++) if(avg != milk[i]) poured++; if(poured == 0){ out.println("Exemplary pages."); return; } if(poured == 2){ int less = -1; for(int i = 0; i < N; i++) if(milk[i] < avg) less = i; int high = -1; for(int i = 0; i < N; i++) if(milk[i] > avg) high = i; if(high != -1 && less != -1 && milk[high] - avg == avg - milk[less]){ out.println((avg - milk[less])+" ml. from cup #"+ (less+1) + " to cup #"+ (high + 1) +"."); } else{ out.println("Unrecoverable configuration."); } } else{ out.println("Unrecoverable configuration."); } } //----------------------------------------------------------- public static void main(String[] args) { new Main().run(); } public void debug(Object... arr){ System.out.println(Arrays.deepToString(arr)); } public void print1Int(int[] a){ for(int i = 0; i < a.length; i++) System.out.print(a[i] + " "); System.out.println(); } public void print2Int(int[][] a){ for(int i = 0; i < a.length; i++){ for(int j = 0; j < a[0].length; j++){ System.out.print(a[i][j] + " "); } System.out.println(); } } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = null; solve(); in.close(); out.close(); } catch (IOException e) { System.exit(0); } } public String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } PrintWriter out; BufferedReader in; StringTokenizer tok; }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
60da87317a2445e2735b527f75800121
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String args[])throws IOException { new B().run(); } void run()throws IOException { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(in.readLine()); int a[]=new int[n]; int temp[]=new int[n]; double w=0; for(int i=1;i<=n;i++) { a[i-1]=Integer.parseInt(in.readLine()); temp[i-1]=a[i-1]; w+=a[i-1]; } w=w/(double)n; Arrays.sort(a); if(a[0]==a[n-1]) { System.out.println("Exemplary pages."); return; } else if(n<=2) { if(n==1) { System.out.println("Exemplary pages."); return; } else if(n==2) { if(a[0]==a[1]) { System.out.println("Exemplary pages."); return; } else { int val=(a[1]-a[0])/2; double x=(double)(a[0]+a[1])/2.0; if(x-(int)x>0.0) System.out.println("Unrecoverable configuration."); else if(temp[0]<temp[1]) { System.out.println(val+" ml. from cup #1 to cup #2."); } else System.out.println(val+" ml. from cup #2 to cup #1."); } } } else if(n==3) { double avg=(a[0]+a[1]+a[2])/3.0; if((double)avg-(int)avg>0.0 || (double)avg!=((double)(a[0]+a[n-1])/2.0)) { System.out.println("Unrecoverable configuration."); } else { int x=0,y=0; for(int i=0;i<3;i++) { if(temp[i]==(int)avg) { x=(i+1)%3; y=(i+2)%3; } } if(temp[x]>temp[y]) { int j=x; x=y; y=j; } x+=1; y+=1; int val=(a[n-1]-a[0])/2; System.out.println(val+" ml. from cup #"+x+" to cup #"+y+"."); } } else { int x=-1,y=-1; if(a[1]==a[n-2] && ((double)(a[0]+a[n-1])/2.0)==w) { for(int i=0;i<n;i++) { if(temp[i]!=(int)w && x==-1) { x=i; } else if(temp[i]!=(int)w) { y=i; break; } } if(temp[x]>temp[y]) { int j=x; x=y; y=j; } x+=1; y+=1; int val=(a[n-1]-a[0])/2; System.out.println(val+" ml. from cup #"+x+" to cup #"+y+"."); } else { System.out.println("Unrecoverable configuration."); } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
86f2999f1df7d17d46a670dbda0f3351
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.BufferedReader; //import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; //import java.io.FileReader; //import java.io.FileWriter; //import java.lang.StringBuilder; //import java.util.StringTokenizer; //import java.lang.Comparable; //import java.util.Arrays; //import java.util.HashMap; //import java.util.ArrayList; public class HelpChefGerasim { //static BufferedReader in = new BufferedReader(new FileReader("input.txt")); //static PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(System.out); //static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException { int n = Integer.parseInt(in.readLine()); int[] juice = new int[n]; int t = 0; for(int i = 0; i < n; i++) { juice[i] = Integer.parseInt(in.readLine()); t += juice[i]; } if(t % n != 0) { out.print("Unrecoverable configuration"); } else { int m = t / n; int nd = 0; for(int i = 0; i < n; i++) { if(juice[i] != m) { nd++; } } if(nd == 0) { out.print("Exemplary pages"); } else { if(nd == 2) { int imin = 0; int imax = 0; int d = 0; for(int i = 0; i < n; i++) { if(juice[i] > m) { imin = i; d = juice[i] - m; } else if(juice[i] < m) { imax = i; } } imax++; imin++; out.print(d); out.print(" ml. from cup #"); out.print(imax); out.print(" to cup #"); out.print(imin); } else { out.print("Unrecoverable configuration"); } } } out.print("."); out.close(); } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
fc6b3cf565e733694cc79064c9be25d4
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.io.Writer; import java.io.OutputStreamWriter; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author tarek */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); BHelpChefGerasim solver = new BHelpChefGerasim(); solver.solve(1, in, out); out.close(); } static class BHelpChefGerasim { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.readInt(); int[] a = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { a[i] = in.readInt(); sum += a[i]; } int u = sum / n; if (u * n != sum) { out.printLine("Unrecoverable configuration."); return; } List<Integer> form = new ArrayList<>(), to = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a[i] > u) { to.add(i); } if (a[i] < u) { form.add(i); } } if (form.size() == 0) { out.printLine("Exemplary pages."); return; } if (form.size() != 1 || to.size() != 1) { out.printLine("Unrecoverable configuration."); return; } out.printLine(String.format("%d ml. from cup #%d to cup #%d.", a[to.get(0)] - u, form.get(0) + 1, to.get(0) + 1)); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
66d6f652bcbf28c148f1eb08f3af5466
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.*; import java.util.*; import java.util.HashSet; import java.util.Scanner; import java.util.Set; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.text.DecimalFormat; import java.lang.Math; import java.util.Iterator; public class b88{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); float avg = 0; ArrayList<Integer> A = new ArrayList<Integer>(); for(int i = 0; i < n; i++){ A.add(sc.nextInt()); avg += (float)A.get(i); } avg = (float)avg/n; int count = 0; for(int i = 0; i < A.size(); i++){ if((float)A.get(i)!=avg){ count++; } } if(count>2){ System.out.println("Unrecoverable configuration."); } else if(count == 0){ System.out.println("Exemplary pages."); } else if( count == 2){ ArrayList<Integer> B = new ArrayList<Integer>(A); Collections.sort(B); if(B.get(B.size()-1)-(int)avg ==(int)avg-B.get(0)){ System.out.println((B.get(B.size()-1)-(int)avg) +" ml. from cup #" + (A.indexOf(B.get(0))+1) + " to cup #"+ (A.indexOf(B.get(B.size()-1))+1) +"."); } else{ System.out.println("Unrecoverable configuration."); } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
ef3cf40a238935c41594a7e51f4f7ee3
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class HelpChefGerasim { static class Cal implements Comparable<Cal>{ int in=0,val=0,count=0; Cal(){ in=0; val=0; count=0; } public int compareTo(Cal o){ if(count!=o.count) return count-o.count; else return val-o.val; } } public static void main(String asd[])throws Exception { Scanner in=new Scanner(System.in); int n=in.nextInt(); Cal a[]=new Cal[10001]; for(int i=0;i<10001;i++) a[i]=new Cal(); int b[]=new int[10001];int flag=0,k=0; for(int i=0;i<n;i++) { int q=in.nextInt(); if(b[q]==0){ if(k==3){ flag=1; } else{ a[q].in=i; a[q].val=q; a[q].count=1; //System.out.println(q +" "+k); k++; b[q]=1; } } else{ a[q].count+=1; } } Arrays.sort(a); if(flag==1) System.out.println("Unrecoverable configuration."); else{ if(k==1) System.out.println("Exemplary pages."); else if(k==2){ int r=a[10000].count; int q=a[10000-1].count; if(r==1 && q==1) { if((a[10000].val+a[10000-1].val)%2==0) System.out.println((a[10000].val+a[10000-1].val)/2+" ml. from cup #"+(a[10000-1].in+1)+" to cup #"+(a[10000].in+1)+"."); else System.out.println("Unrecoverable configuration."); } else System.out.println("Unrecoverable configuration."); } else{ int r=a[10000-2].count; int q=a[10000-1].count; // System.out.println(a[0].count); if(r==1 && q==1 && a[10000].count==1){ int t=Math.abs(a[10000-1].val-a[10000-2].val); int tt=Math.abs(a[10000].val-a[10000-1].val); if(t==tt){ System.out.println(t+" ml. from cup #"+(a[10000-2].in+1)+" to cup #"+(a[10000].in+1)+"."); } else{ System.out.println("Unrecoverable configuration."); } } else if(r==1 && q==1){ int t=Math.abs(a[10000].val-a[10000-2].val); int tt=Math.abs(a[10000].val-a[10000-1].val); if(t==tt) { System.out.println(t+" ml. from cup #"+(a[10000-2].in+1)+" to cup #"+(a[10000-1].in+1)+"."); } else { System.out.println("Unrecoverable configuration."); } } else System.out.println("Unrecoverable configuration."); } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
5bcb6e8e2e8855577aad5ddd62add4f6
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class popo { public static boolean prime[]; public static ArrayList[] ad=new ArrayList[2555]; public static ArrayList<Long> xor1,xor2; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.nextInt(); long [] a = new long [n]; long sum = 0; for (int i = 0; i < a.length; i++) sum += a[i] = in.nextInt(); ArrayList<Integer> l = new ArrayList<>(); if (sum % n != 0) { System.out.println("Unrecoverable configuration."); return; } sum /= n; for (int i = 0; i < a.length; i++) if (a[i] != sum) l.add(i); if (n == 1 || l.size() == 0) { System.out.println("Exemplary pages."); } else if (l.size() != 2) { System.out.println("Unrecoverable configuration."); } else { long d1 = sum - a[l.get(0)]; long d2 = sum - a[l.get(1)]; int from = d1 > d2 ? l.get(0) : l.get(1) ; int to = d1 > d2 ? l.get(1) : l.get(0) ; if (d1 == -1 * d2) System.out.printf("%d ml. from cup #%d to cup #%d.\n",Math.abs(d1), ++from, ++to); else System.out.println("Unrecoverable configuration."); } out.close(); } 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); } } static long setbits(long i) { long count = 0; while (i>0) { count += i & 1; i >>= 1; } return count; } static ArrayList<Long> sieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. prime=new boolean[1000001]; for(int i=0;i<n;i++) prime[i] = true; for(long p = 2; p*p <=n; p++) { // If prime[p] is not changed, then it is a prime if(prime[(int)p] == true) { // Update all multiples of p for(long i = p*2; i <= n; i += p) { prime[(int) i] = false; } } } ArrayList<Long> aa=new ArrayList<>(); for (long i=0;i<n;i++) { if(prime[(int)i]) aa.add(i); } return aa; // Print all prime numbers /* for(int i = 2; i <= n; i++) { if(prime[i] == true) System.out.print(i + " "); } */ } static class coor{ int x; int y; public coor(int x, int y) { this.x = x; this.y = y; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[8192]; private int curChar, snumChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) c = snext(); int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
e93311b5eeb64e3a446e6a16052d0d0f
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.*; import java.math.BigDecimal; import java.net.URL; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine(), " :"); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } void solve() throws IOException { int n = readInt(); int[] a = readIntArray(n); int sum = 0; for (int x : a) sum += x; if (sum % n != 0) { out.println("Unrecoverable configuration."); return; } int avg = sum / n; int prev = -1; List<Integer> indexes = new ArrayList<>(); for (int i = 0; i < n; i++) { if (a[i] != avg) indexes.add(i); } if (indexes.size() == 0) { out.println("Exemplary pages."); return; } if (indexes.size() != 2) { out.println("Unrecoverable configuration."); return; } int first = indexes.get(0); int second = indexes.get(1); if (a[first] > a[second]) { int t = first; first = second; second = t; } out.println((-a[first] + avg) + " ml. from cup #" + (first + 1) + " to cup #" + (second + 1) + "."); } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
66a61a29ea17851d96a5a2955ab8a3e4
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.Comparator; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Random; import java.io.Writer; import java.util.HashSet; import java.util.List; import java.io.IOException; import java.util.Arrays; import java.util.InputMismatchException; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.TreeSet; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, OutputWriter out){ int n = in.ri(); int[] a = IOUtils.readIntArray(in, n); int sum = (int) ArrayUtils.sumArray(a); if (sum % n != 0){ out.printLine("Unrecoverable configuration."); return; } int avg = sum / n; int wrong = 0; for(int val : a){ if (val != avg){ wrong++; } } if (wrong > 2 || wrong == 1){ out.printLine("Unrecoverable configuration."); return; } if (wrong == 0){ out.printLine("Exemplary pages."); return; } boolean foundfirstwrong = false; int firstwrongindex = - 1; for(int i = 0; i < a.length; i++) { int val = a[i]; if (val != avg && !foundfirstwrong){ firstwrongindex = i; foundfirstwrong = true; } else if (val != avg){ int diff = Math.abs(a[firstwrongindex] - a[i]) / 2; if (a[i] > a[firstwrongindex]){ out.printLine(diff + " ml. from cup #" + (firstwrongindex +1) + " to cup #" + (i + 1) + "."); } else{ out.printLine(diff + " ml. from cup #" + (i + 1) + " to cup #" + (firstwrongindex + 1) + "."); } return; } } } } 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 ri(){ return readInt(); } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } class ArrayUtils { public static long sumArray(int[] array) { long result = 0; for (int element : array) result += element; return result; } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
be4b85f832d33087a12db2de056d340f
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.util.Scanner; public class Main { public static Scanner in = new Scanner(System.in); public static void main(String[] args) throws Exception { int n; n=in.nextInt(); double sum=0; int a[]=new int[1001]; for(int i=0;i<n;i++) { a[i]=in.nextInt(); sum+=a[i]; } double ans=sum/n; if(ans%1!=0){ System.out.println("Unrecoverable configuration."); System.exit(0); } int k=0; for(int i=0;i<n;i++) { if(Math.abs(a[i]-ans)!=0)k++; } // System.out.println(ans); if(k!=2 && k!=0) { System.out.println("Unrecoverable configuration."); System.exit(0); } if(k==0) { System.out.println("Exemplary pages."); System.exit(0); } if(k==2) { int fi = 0,se = 0,di1 = 0,di2 = 0; for(int i=0;i<n;i++) { if(Math.abs(a[i]-ans)!=0 && di1==0){di1= (int) Math.abs(a[i]-ans); fi=i;} if(Math.abs(a[i]-ans)!=0 && di1!=0){di2=(int) Math.abs(a[i]-ans); se=i;} } if(((di1+di2)/2)%1!=0) { System.out.println("Unrecoverable configuration."); System.exit(0); } else{ System.out.print(((di1+di2)/2)+" ml. from cup #"); int mi=Math.min(a[fi],a[se]); if(mi==a[fi]) { se++;fi++; System.out.print(fi+" to cup #"+se+"."); } else{ se++;fi++; System.out.print(se+" to cup #"+fi+"."); } } } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
b5019575b76a35d09774735ccf3849f7
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class HelpChefGerasim implements Closeable { private InputReader in = new InputReader(System.in); private PrintWriter out = new PrintWriter(System.out); public void solve() { int n = in.ni(); int total = 0; int[] x = new int[n]; for (int i = 0; i < n; i++) { x[i] = in.ni(); total += x[i]; } double average = ((double) total / n); int diff = 0; for (int i = 0; i < n; i++) { if (x[i] != average) diff++; } if (diff == 0) { out.println("Exemplary pages."); } else if (diff > 0 && diff != 2) { out.println("Unrecoverable configuration."); } else if (diff == 2) { int from = 0, to = 0; for (int i = 0; i < n; i++) { if (x[i] < average) from = i + 1; else if (x[i] > average) to = i + 1; } int t = (x[to - 1] - x[from - 1]); if (t % 2 == 1) { out.println("Unrecoverable configuration."); } else { out.printf("%d ml. from cup #%d to cup #%d.\n", t / 2, from, to); } } } @Override public void close() throws IOException { in.close(); out.close(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int ni() { return Integer.parseInt(next()); } public long nl() { return Long.parseLong(next()); } public void close() throws IOException { reader.close(); } } public static void main(String[] args) throws IOException { try (HelpChefGerasim instance = new HelpChefGerasim()) { instance.solve(); } } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
196ac7a44f712b0574fc5a99997b42ac
train_002.jsonl
1311346800
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup to another. Now Gerasim wants to check his hypothesis. The good thing is that chef Gerasim always pour the same number of milliliters of juice to all cups in the royal kitchen. Having thoroughly measured the juice in each cup, Gerasim asked you to write a program that will determine from which cup juice was poured to which one; otherwise, the program should determine that this time the pages set the table diligently.To simplify your task we shall consider the cups to be bottomless so that the juice never overfills a cup and pours out, however much it can be. Besides, by some strange reason in a far away kingdom one can only pour to a cup or from one cup to another an integer number of milliliters of juice.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; public class B implements Closeable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); StringTokenizer stringTokenizer; B() throws IOException { // reader = new BufferedReader(new FileReader("input.txt")); // writer = new PrintWriter(new FileWriter("output.txt")); } String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } int pow(int x, long k) { int result = 1; while (k > 0) { if (k % 2 == 1) { result = product(result, x); } x = product(x, x); k /= 2; } return result; } @SuppressWarnings("unchecked") void solve() throws IOException { int n = nextInt(); int[] v = new int[n]; int sum = 0; for (int i = 0; i < n; i++) { v[i] = nextInt(); sum += v[i]; } int u = sum / n; if(u * n != sum) { writer.println("Unrecoverable configuration."); return; } List<Integer> from = new ArrayList<>(), to = new ArrayList<>(); for(int i = 0; i < n; i++) { if(v[i] > u) { to.add(i); } if(v[i] < u) { from.add(i); } } if(from.size() == 0) { writer.println("Exemplary pages."); return; } if(from.size() != 1 || to.size() != 1) { writer.println("Unrecoverable configuration."); return; } writer.println(String.format("%d ml. from cup #%d to cup #%d.", v[to.get(0)] - u, from.get(0) + 1, to.get(0) + 1)); } public static void main(String[] args) throws IOException { try (B b = new B()) { b.solve(); } } @Override public void close() throws IOException { reader.close(); writer.close(); } }
Java
["5\n270\n250\n250\n230\n250", "5\n250\n250\n250\n250\n250", "5\n270\n250\n249\n230\n250"]
0.5 second
["20 ml. from cup #4 to cup #1.", "Exemplary pages.", "Unrecoverable configuration."]
null
Java 8
standard input
[ "implementation", "sortings" ]
7bfc0927ea7abcef661263e978612cc5
The first line contains integer n — the number of cups on the royal table (1 ≤ n ≤ 1000). Next n lines contain volumes of juice in each cup — non-negative integers, not exceeding 104.
1,300
If the pages didn't pour the juice, print "Exemplary pages." (without the quotes). If you can determine the volume of juice poured during exactly one juice pouring, print "v ml. from cup #a to cup #b." (without the quotes), where v represents the volume of poured juice, a represents the number of the cup from which the juice was poured (the cups are numbered with consecutive positive integers starting from one in the order in which the cups are described in the input data), b represents the number of the cup into which the juice was poured. Finally, if the given juice's volumes cannot be obtained using no more than one pouring (for example, the pages poured the juice from one cup to another more than once or the royal kitchen maids poured the juice into the cups incorrectly), print "Unrecoverable configuration." (without the quotes).
standard output
PASSED
762958faa934cef8788f027cad706973
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class Roads { public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // para String line; while ((line = in.readLine()) != null) { String[] tokens = line.split(" "); int n = Integer.parseInt(tokens[0]); int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { line = in.readLine(); tokens = line.split(" "); for (int j = 0; j < n; j++) { a[i][j] = Integer.parseInt(tokens[j]); } } StringBuffer result = new StringBuffer(); line = in.readLine(); tokens = line.split(" "); for (int k = Integer.parseInt(tokens[0]); k-- > 0; ) { // 1-300 line = in.readLine(); tokens = line.split(" "); int x = Integer.parseInt(tokens[0]) - 1; int y = Integer.parseInt(tokens[1]) - 1; int z = Integer.parseInt(tokens[2]); a[x][y] = a[y][x] = Math.min(a[x][y], z); for (int t : new int[]{x, y}) { for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (a[i][j] > a[i][t] + a[t][j]) { a[i][j] = a[j][i] = a[i][t] + a[t][j]; } } } } long sum = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { sum += a[i][j]; } } result.append(sum); result.append(" "); } System.out.println(result.replace(result.length() - 1, result.length(), "")); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
341f7fd5b01d1c1169baefde81766fb1
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.*; import static java.lang.Math.*; import java.util.*; import java.util.function.*; import java.lang.*; public class Main { final static boolean debug = false; final static String fileName = ""; final static boolean useFiles = false; public static void main(String[] args) throws FileNotFoundException { long start; if (debug) start = System.nanoTime(); InputStream inputStream; OutputStream outputStream; if (useFiles) { inputStream = new FileInputStream(fileName + ".in"); outputStream = new FileOutputStream(fileName + ".out"); } else { inputStream = System.in; outputStream = System.out; } InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(in, out); solver.solve(); if(debug) out.println((System.nanoTime() - start) / 1e+9); out.close(); } } class Task { void update(int[][] d, int k){ for (int i = 0; i < d.length; i++){ for (int j = 0; j < d.length; j++){ d[i][j] = min(d[i][j], d[i][k] + d[k][j]); } } } public void solve() { int n = in.nextInt(); int[][] d = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) d[i][j] = in.nextInt(); for (int k = 0; k < n; k++) { update(d, k); } int q = in.nextInt(); for (int t = 0; t < q; t++) { int a = in.nextInt() - 1; int b = in.nextInt() - 1; int w = in.nextInt(); if (d[a][b] > w) { d[b][a] = d[a][b] = w; update(d, a); update(d, b); } long sum = 0; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) sum += d[i][j]; out.print(sum / 2 + " "); } } private InputReader in; private PrintWriter out; Task(InputReader in, PrintWriter out) { this.in = in; this.out = out; } } 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 double nextDouble(){ return Double.parseDouble(next()); } public int nextInt() { return Integer.parseInt(next()); } public char[] nextCharArray(){ return next().toCharArray(); } public int[] nextIntArray(int n){ int[] result = new int[n]; for (int i = 0; i < n; i++) result[i] = nextInt(); return result; } public long[] nextLongArray(int n){ long[] result = new long[n]; for (int i = 0; i < n; i++) result[i] = nextLong(); return result; } public long nextLong(){ return Long.parseLong(next()); } public byte nextByte(){ return Byte.parseByte(next()); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
636c12f75c133b5f44b6ac927098402d
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; public class MyClass { public static void main(String args[]) { Scanner kb=new Scanner(System.in); int cities=kb.nextInt(); int [][]mat=new int [cities][cities]; for(int i=0;i<cities;i++){ for(int j=0;j<cities;j++){ mat[i][j]=kb.nextInt(); } } int roads=kb.nextInt(); for(int i=0;i<roads;i++){ int a=kb.nextInt()-1; int b=kb.nextInt()-1; int c=kb.nextInt(); if(c<mat[a][b]){ mat[a][b]=c; mat[b][a]=c; for(int j=0;j<cities;j++){ for(int f=0;f<cities;f++){ if(mat[j][f]>mat[j][a]+mat[a][b]+mat[b][f]){ mat[j][f]=mat[j][a]+mat[a][b]+mat[b][f]; mat[f][j]=mat[j][a]+mat[a][b]+mat[b][f]; } } } for(int j=0;j<cities;j++){ for(int f=0;f<cities;f++){ if(mat[j][f]>mat[j][b]+mat[b][a]+mat[a][f]){ mat[j][f]=mat[j][b]+mat[b][a]+mat[a][f]; mat[f][j]=mat[j][b]+mat[b][a]+mat[a][f]; } } } } long sum=0; for(int [] arr:mat){ for(int k:arr){ sum+=k; } } System.out.print(sum/2+" "); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
9620735699a77ab600d47d7d651b78f5
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; public class Problem6 { static int n; static int m; static int[][] dist; public static void main( String[] args ) { Scanner input = new Scanner( System.in ); // Get the number of cities n = input.nextInt(); // Initialize the 2D distance array dist = new int[n+1][n+1]; // Get the distances of each bidirectional road for ( int i = 1 ; i <= n ; i++ ) for ( int j = 1 ; j <= n ; j++ ) dist[i][j] = input.nextInt(); // Floyd Warshall Algorithm // Calculate the distances for each pair of cities for ( int k = 1 ; k <= n ; k++ ) for ( int i = 1 ; i <= n ; i++ ) for ( int j = 1 ; j <= n ; j++ ) { // Path i -> j OR i -> k -> j dist[i][j] = Math.min( dist[i][j] , dist[i][k] + dist[k][j] ); } // Get the number of planned roads m = input.nextInt(); for ( int t = 0 , x , y , z ; t < m ; t++ ) { // Get 1st city x = input.nextInt(); // Get 2nd city y = input.nextInt(); // Get the length of new road z = input.nextInt(); // Update the distances dist[x][y] = Math.min( dist[x][y] , z ); dist[y][x] = Math.min( dist[y][x] , z ); // Update the distances for each pair of cities for ( int i = 1 ; i <= n ; i++ ) for ( int j = 1 ; j <= n ; j++ ) { // Path i -> j OR i -> x -> y -> j dist[i][j] = Math.min( dist[i][j] , dist[i][x] + dist[x][y] + dist[y][j] ); // Path i -> j OR i -> y -> x -> j dist[i][j] = Math.min( dist[i][j] , dist[i][y] + dist[y][x] + dist[x][j] ); } long sumOfShortestDistances = 0; // Calculate the sum of shortest distances of all pairs for ( int i = 1 ; i <= n ; i++ ) for ( int j = i + 1 ; j <= n ; j++ ) sumOfShortestDistances += (long) dist[i][j]; System.out.print( sumOfShortestDistances + " " ); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
ea09a27db773293d4c64850a7013bcce
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = sc.nextInt(); long sum = 0; int[][] d = new int[n][n]; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) sum += d[i][j] = sc.nextInt(); sum /= 2; int k = sc.nextInt(); while(k-->0) { int a = sc.nextInt() - 1, b = sc.nextInt() - 1, c = sc.nextInt(); for(int x = 0; x < n; ++x) for(int y = x + 1; y < n; ++y) { int propD = Math.min(d[x][a] + c + d[b][y], d[x][b] + c + d[a][y]); if(propD < d[x][y]) { sum += propD - d[x][y]; d[x][y] = d[y][x] = propD; } } out.print(sum + " "); } out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
a6583db1577c6fbec5c75fe34c65cd2c
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000 * 1000 * 1000 + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; void solve() throws IOException { int n = nextInt(); int[][] mat = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { mat[i][j] = nextInt(); } } int k = nextInt(); for (int p = 0; p < k; p++) { int[][] tmp = new int[n][n]; for (int i1 = 0; i1 < n; i1++) { for (int j1 = 0; j1 < n; j1++) { tmp[i1][j1] = mat[i1][j1]; } } int a = nextInt() - 1; int b = nextInt() - 1; int c = nextInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int min = tmp[i][j]; min = Math.min(min, tmp[i][a] + c + tmp[b][j]); min = Math.min(min, tmp[i][b] + c + tmp[a][j]); tmp[i][j] = min; } } long sum = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { sum += tmp[i][j]; } } out(sum + " "); mat = tmp; } } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { System.out.format("%.9f%n", val); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
c856f6dcbe4f3001474118227b504f42
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.util.StringTokenizer; /** * 25C * * @author artyom */ public class RoadsInBerland implements Runnable { private BufferedReader in; private PrintStream out; private StringTokenizer tok; private void solve() throws IOException { int n = nextInt(); int[][] mx = new int[n][n]; long total = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int val = nextInt(); mx[i][j] = val; if (j > i) { total += val; } } } StringBuilder sb = new StringBuilder(); for (int i = 0, m = nextInt(); i < m; i++) { int a = nextInt() - 1, b = nextInt() - 1, c = nextInt(); for (int j = 0; j < n; j++) { for (int k = j + 1; k < n; k++) { int dist = mx[j][a] + c + mx[b][k]; if (dist < mx[j][k]) { total -= mx[j][k] - dist; mx[j][k] = mx[k][j] = dist; } dist = mx[j][b] + c + mx[a][k]; if (dist < mx[j][k]) { total -= mx[j][k] - dist; mx[j][k] = mx[k][j] = dist; } } } sb.append(total).append(' '); } out.print(sb); } //-------------------------------------------------------------- public static void main(String[] args) { new RoadsInBerland().run(); } @Override public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = System.out; tok = null; solve(); in.close(); } catch (IOException e) { System.exit(0); } } private String nextToken() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
94f42e2cb4a72b9a640413b27074109d
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class RoadsInBerland { static int n,AdjMat[][]; static long sum; public static void Warshall(int a,int b,int c) { for (int i=0;i<n;i++) { for (int j=0;j<n;j++) { AdjMat[i][j] = Math.min(AdjMat[i][j], AdjMat[i][a]+c+AdjMat[b][j]); AdjMat[i][j] = Math.min(AdjMat[i][j], AdjMat[i][b]+c+AdjMat[a][j]); // System.out.print(AdjMat[i][j]+" "); } // System.out.println(); } } public static long sumShortestPaths() { long sum = 0; for (int i=0;i<n;i++) for (int j=i+1;j<n;j++) { sum+=AdjMat[i][j]; } return sum; } public static void main(String args[]) throws NumberFormatException, IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); n = Integer.parseInt(br.readLine()); AdjMat = new int[n][n]; for (int i=0;i<n;i++) { StringTokenizer st = new StringTokenizer(br.readLine()); for (int j=0;j<n;j++) { AdjMat[i][j] = Integer.parseInt(st.nextToken()); sum+=AdjMat[i][j]; } } sum/=2; int k = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); for (int i=0;i<k;i++) { StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken())-1; int b = Integer.parseInt(st.nextToken())-1; int c = Integer.parseInt(st.nextToken()); if (c>=AdjMat[a][b]) { sb.append(sum+" "); continue; } AdjMat[a][b] = Math.min(AdjMat[a][b], c); AdjMat[b][a] = Math.min(AdjMat[b][a], c); Warshall(a,b,c); sum = sumShortestPaths(); sb.append(sum+" "); } System.out.println(sb); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
35e639b6794b220f8cadd3a4efe22469
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.*; public class Berland { private static int[][] dis; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); long sum = 0; int a, b, c; int n = scanner.nextInt(); int[][] m = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { m[i][j] = scanner.nextInt(); } } FloydWarshall(m); int k = scanner.nextInt(); for (int y = 0; y < k; y++) { a = scanner.nextInt(); b = scanner.nextInt(); c = scanner.nextInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dis[i][j] = Math.min(dis[i][j], dis[i][a - 1] + dis[b - 1][j] + c); dis[i][j] = Math.min(dis[i][j], dis[i][b - 1] + dis[a - 1][j] + c); } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum += dis[i][j]; } } sum = sum / 2; System.out.print(sum + " "); sum = 0; } System.out.println(); } private static void FloydWarshall(int[][] matrix) { int n = matrix.length; dis = matrix.clone(); for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dis[i][j] = Math.min(dis[i][j], (dis[i][k] + dis[k][j])); } } } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
c57b8c2d7dcf678a3ddc67522d350644
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; public class RodesinBerlandB25C100th { public static void main(String args[]) { Scanner s=new Scanner(System.in); StringBuilder ans=new StringBuilder(); int n=s.nextInt(); long p[][]=new long[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) p[i][j]=s.nextLong(); } int m=s.nextInt(); for(int k=0;k<m;k++) { int a=s.nextInt()-1; int b=s.nextInt()-1; long c=s.nextLong(); long ans1=0; for(int i=0;i<n;i++) { for(int j=i;j<n;j++) { if(p[i][j]>(p[i][a]+c+p[b][j])) { p[i][j]=(p[i][a]+c+p[b][j]); p[j][i]=(p[i][a]+c+p[b][j]); } if(p[i][j]>(p[i][b]+c+p[a][j])) { p[i][j]=(p[i][b]+c+p[a][j]); p[j][i]=(p[i][b]+c+p[a][j]); } ans1+=p[i][j]; //System.out.print(p[i][j]); } //System.out.println(); } ans.append(ans1+" "); } System.out.println(ans); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
76e552610d8c92027e74def18c5e24dc
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Main { static class Reader { private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;} public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];} public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;} public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();} public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;} public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;} public double d() throws IOException {return Double.parseDouble(s()) ;} public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;} } // |----| /\ | | ----- | // | / / \ | | | | // |--/ /----\ |----| | | // | \ / \ | | | | // | \ / \ | | ----- ------- public static void main(String[] args)throws IOException { Reader sc=new Reader(); PrintWriter out=new PrintWriter(System.out); int n=sc.i(); int arr[][]=new int[n][n]; for(int i=0;i<n;i++)arr[i]=sc.arr(n); int t=sc.i(); while(t-->0) { int a=sc.i(); int b=sc.i(); a--;b--; int dis=sc.i(); if(arr[a][b]>dis) { arr[a][b]=dis; arr[b][a]=dis; for(int i=0;i<n;i++) for(int j=0;j<n;j++) arr[i][j]=Math.min(arr[i][j],Math.min(arr[i][a]+arr[a][b]+arr[b][j],arr[j][a]+arr[a][b]+arr[b][i])); } long sum=0; for(int i=0;i<n;i++)for(int j=0;j<n;j++)sum+=(long)arr[i][j]; out.println(sum/2); } out.flush(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
1bf3839e61193f23923d5ff45645697b
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; import java.math.*; import java.lang.*; import java.io.*; public class Main{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); long[][] g = new long[n][n]; for(int i=0;i<n; i++) { for(int j=0; j<n; j++) { g[i][j] = scan.nextLong(); } } int l = scan.nextInt(); for(int i=0; i<l; i++) { int a = scan.nextInt()-1; int b = scan.nextInt()-1; long c = scan.nextLong(); for(int j=0; j<n; j++) { for(int k=0; k<n; k++) { long l1 = g[j][a]+c+g[b][k]; long l2 = g[j][b]+c+g[a][k]; long new_l = Math.min(l1,l2); long newll = Math.min(g[j][k],new_l); g[j][k] = newll; g[k][j] = newll; } } long ans = 0; for(int j=0; j<n; j++) { for(int k=j+1; k<n; k++) { ans += g[j][k]; } } System.out.println(ans); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
ca44a051299f6706ee466963f921d28b
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class RoadsInBerland { static int [][] grid; static int V; static final int oo = (int)1e9; public static void Floyd(){ for(int k = 0;k < V;k++) for(int i = 0;i < V;i++) for(int j = 0;j < V;j++) grid[i][j] = Math.min(grid[i][j], grid[i][k] + grid[k][j]); } public static void main(String[] args) throws IOException { MyScanner sc = new MyScanner(System.in); PrintWriter pw = new PrintWriter(System.out); V = sc.nextInt(); grid = new int [V][V]; for(int i = 0;i < V;i++){ Arrays.fill(grid[i], oo); grid[i][i] = 0; } for(int i = 0;i < V;i++) for(int j = 0;j < V;j++) grid[i][j] = grid[j][i] = sc.nextInt(); //Floyd(); int k = sc.nextInt(); while(k-- > 0){ int u = sc.nextInt() - 1; int v = sc.nextInt() - 1; int c = sc.nextInt(); long ans = 0; for(int i = 0;i < V;i++){ for(int j = 0;j < V;j++) { grid[i][j] = Math.min(grid[i][j], Math.min(grid[i][u] + c + grid[v][j], grid[i][v] + c + grid[u][j])); ans += grid[i][j]; } } pw.println(ans >> 1); } pw.close(); } static class MyScanner { StringTokenizer st; BufferedReader br; public MyScanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
970d838b56f7bec415f353999b0cc60a
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //package CP; import java.io.*; import java.util.*; public class C25 { public static void main(String args[])throws IOException { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int arr[][]=new int[n+1][n+1]; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { arr[i][j]=sc.nextInt(); } } int q=sc.nextInt(); for(int z=1;z<=q;z++) { int st=sc.nextInt(); int end=sc.nextInt(); int wt=sc.nextInt(); arr[st][end]=arr[end][st]=Math.min(arr[st][end],wt); long r=0; for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(i!=j) { arr[i][j]=Math.min(arr[i][j],arr[i][st]+arr[st][end]+arr[end][j]); arr[i][j]=Math.min(arr[i][j],arr[i][end]+arr[end][st]+arr[st][j]); } r+=arr[i][j]; } } System.out.print(r/2+" "); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
39828e71114db9c888a6c4f5c022c474
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.*; import java.util.*; public class RoadsInBerland{ static int MAX = 301; static int INF = Integer.MAX_VALUE; static int matrix[][] = new int[MAX][MAX]; static int min(int a , int b){ return a <= b ? a : b; } static long findSum(int a, int b , int weight, int n, long oldSum){ //a new road is added between `a` and `b` //n is size of matrix given 1 indexed but here implemented as 0 indexed int min = INF; long sum = 0; int matrix2[][] = new int[n][n]; if (matrix[a][b] > weight){ matrix[a][b] = weight; matrix[b][a] = weight; //update weights for (int i = 0 ; i < n ; ++i){ for (int j = 0 ; j < n ; ++j){ min = INF; min = min(matrix[i][j] , min (matrix[i][a] + weight + matrix[b][j], matrix[i][b] + weight + matrix[a][j]) ); matrix2[i][j] = min; sum += min; } } for (int i = 0 ; i < n ; ++i) for (int j = 0 ; j < n ; ++j) matrix[i][j] = matrix2[i][j]; }else{ sum = oldSum; } return sum; } public static void main(String args[]) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); long sum = 0; int n = Integer.parseInt(br.readLine()); for (int i = 0 ; i < n ; ++i){ StringTokenizer st = new StringTokenizer(br.readLine()); for (int j = 0 ; j < n ; ++j){ matrix[i][j] = Integer.parseInt(st.nextToken()); sum += matrix[i][j]; } } int k = Integer.parseInt(br.readLine()); StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < k ; ++i){ StringTokenizer st = new StringTokenizer(br.readLine()); int a, b, c; a = Integer.parseInt(st.nextToken()); b = Integer.parseInt(st.nextToken()); c = Integer.parseInt(st.nextToken()); a--; b--; sum = findSum(a, b, c, n, sum); // System.out.println(sum / 2); sb.append(sum / 2 + " "); } PrintWriter out = new PrintWriter(System.out); out.println(sb); out.close(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
3f086c3826cdaeda73431f32a8c8d463
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(); int adj[][] = new int[n][n]; int dist[][] = new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ adj[i][j] = ni(); dist[i][j] = adj[i][j]; } // System.out.println(Arrays.toString(dist[i])); } // Floyd Warshall. for(int k=0;k<n;k++){ for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ // System.out.println("dist[i][k]="+dist[i][k] + "dist[k][j]="+dist[k][j]); dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } } // for(int i=0;i<n;i++) System.out.println(Arrays.toString(dist[i])); int q = ni(); int prevAns = 0; while(q-->0){ long ans = 0; int a = ni(), b = ni(), c = ni(); dist[a-1][b-1] = Math.min(dist[a-1][b-1], c); dist[b-1][a-1] = Math.min(dist[a-1][b-1], c); int k = a-1; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } k = b-1; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); } } for(k=0;k<n;k++){ dist[a-1][b-1] = Math.min(dist[a-1][b-1], dist[a-1][k] + dist[k][b-1]); dist[b-1][a-1] = Math.min(dist[b-1][a-1], dist[b-1][k] + dist[k][a-1]); } // int ans = 0; for(int i=0;i<n;i++) for(int j=i+1;j<n;j++) ans += dist[i][j]; // prevAns = ans; out.print(ans + " "); } } void run() throws Exception { is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
3a48edbcfd79d97d9717c5d964cc6a9e
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
/** * Created by Alex on 10/20/2014. */ import java.io.*; import java.util.*; public class C25 { BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(nextToken()); } public double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } public long nextLong() throws IOException { return Long.parseLong(nextToken()); } public static void main(String[] args) throws IOException { new C25().run(); } public void solve() throws IOException { int n = nextInt(); int[][] d = new int[n][n]; long sum = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { d[i][j] = nextInt(); sum += d[i][j]; } int k = nextInt(); for (int edge = 0; edge < k; ++edge) { int s = nextInt() - 1; int t = nextInt() - 1; int c = nextInt(); sum = 0; if (d[s][t] > c) { d[s][t] = d[t][s] = c; } for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { if (d[i][j] > d[i][s] + d[s][t] + d[t][j]) { d[i][j] = d[i][s] + d[s][t] + d[t][j]; } if (d[i][j] > d[i][t] + d[t][s] + d[s][j]) { d[i][j] = d[i][t] + d[t][s] + d[s][j]; } sum += d[i][j]; } out.print(sum / 2 + " "); } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
d3f9abd43e4b0dfdc8ada15edfe6be0a
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { 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 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(); } public void flush() { writer.flush(); } } static class IOUtils { public static int[] readIntArray(InputReader in, int size) { int[] array = new int[size]; for (int i = 0; i < size; i++) array[i] = in.readInt(); return array; } } static int n; static int[][][] a; static int[] p; public static void main (String[] args) throws java.lang.Exception { OutputWriter out = new OutputWriter(System.out); InputReader in = new InputReader(System.in); int n = in.readInt(); long psum = 0; int[][] a = new int[n+1][n+1]; for(int i=1; i<=n; i++)for(int j=1; j<=n; j++){a[i][j] = in.readInt(); psum += a[i][j];} psum = psum/2; int q = in.readInt(); for(int w=0; w<q; w++){ int s = in.readInt(); int d = in.readInt(); int len = in.readInt(); if(a[s][d]>len){ a[s][d] = len; a[d][s] = len; for(int i=1; i<=n; i++){ a[i][s] = Math.min(a[i][s], a[i][d]+a[d][s]); a[s][i] = a[i][s]; } for(int i=1; i<=n; i++){ a[i][d] = Math.min(a[i][d], a[i][s]+a[s][d]); a[d][i] = a[i][d]; } long sum = 0; for(int i=1; i<=n; i++){ for(int j=1; j<i; j++){ a[i][j] = Math.min(a[i][j], a[i][s]+a[s][d]+a[d][j]); a[i][j] = Math.min(a[i][j], a[i][d]+a[d][s]+a[s][j]); a[j][i] = a[i][j]; sum += a[j][i]; } } psum = sum; out.print(sum+" "); }else{ out.print(psum+" "); } } out.flush(); out.close(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
be8b4f66b0a5fa3ec7493e6b3a888b5f
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
// http://codeforces.com/problemset/problem/25/C import java.io.*; import java.util.InputMismatchException; public class RoadsInBerland { public static void main(String[] args) throws IOException { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); final int N = in.readInt(); int[][] D = new int[N + 1][N + 1]; int[][] newD = new int[N + 1][N + 1]; int[][] tmp; for (int n = 0; n <= N - 1; ++n) { D[n + 1] = IOUtils.readIntArray(in, N, 1); } final int K = in.readInt(); int a, b, c, i, j; long res; StringBuilder builder = new StringBuilder(); for (int k = 0; k <= K - 1; ++k) { a = in.readInt(); b = in.readInt(); c = in.readInt(); res = 0; for (i = 1; i <= N; ++i) { for (j = 1; j <= N; ++j) { newD[i][j] = Math.min(Math.min(D[i][j], D[i][a] + c + D[b][j]), D[i][b] + c + D[a][j]); res = res + newD[i][j]; } } tmp = D; D = newD; newD = tmp; if (k == K - 1) { builder.append(res / 2); } else { builder.append(res / 2); builder.append(" "); } } out.printLine(builder.toString()); closeStreams(out, in); } private static void closeStreams(OutputWriter out, InputReader in) throws IOException { out.flush(); out.close(); in.close(); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public 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 double readDouble() { 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, readInt()); } 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, readInt()); } if (c < '0' || c > '9') { throw new InputMismatchException(); } m /= 10; res += (c - '0') * m; c = read(); } } 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 boolean isEndOfLine(int c) { if (filter != null) { return filter.isEndOfLine(c); } return c == '\n' || c == '\r' || c == -1; } public String next() { return readString(); } public void close() throws IOException { this.stream.close(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); boolean isEndOfLine(int ch); } } static class IOUtils { public static int[] readIntArray(InputReader in, int elementCount) { return readIntArray(in, elementCount, 0); } public static int[] readIntArray(InputReader in, int elementCount, int startOffset) { int[] array = new int[elementCount + startOffset]; for (int i = 0; i < elementCount; i++) array[i + startOffset] = in.readInt(); return array; } public static long[] readLongArray(InputReader in, int elementCount) { return readLongArray(in, elementCount, 0); } public static long[] readLongArray(InputReader in, int elementCount, int startOffset) { long[] array = new long[elementCount + startOffset]; for (int i = 0; i < elementCount; i++) array[i + startOffset] = in.readLong(); return array; } } 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(); } public void flush() { writer.flush(); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
bcade4b35636da65c9d779ea99bd993d
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; /** * @author Anton Bobukh <abobukh@yandex-team.ru> */ public class Roads { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[][] m = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { m[i][j] = scanner.nextInt(); } } int k = scanner.nextInt(); int[][] p = new int[k][3]; for (int i = 0; i < k; i++) { p[i][0] = scanner.nextInt() - 1; p[i][1] = scanner.nextInt() - 1; p[i][2] = scanner.nextInt(); } long[] result = new long[k]; for (int i = 0; i < p.length; i++) { result[i] = build(m, p[i][0], p[i][1], p[i][2]); } for (long element : result) { System.out.print(element + " "); } } private static long build(int[][] m, int a, int b, int l) { long result = 0; for (int i = 0; i < m.length; i++) { for (int j = 0; j < m[i].length; j++) { m[i][j] = Math.min( Math.min(m[i][j], m[i][a] + l + m[b][j]), m[i][b] + l + m[a][j] ); result += m[i][j]; } } return result / 2; } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
d11ec059c5ca21a6f8559bacca274fc9
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; import java.math.*; import java.lang.*; import java.io.*; public class Main{ public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); long[][] g = new long[n][n]; for(int i=0;i<n; i++) { for(int j=0; j<n; j++) { g[i][j] = scan.nextLong(); } } int l = scan.nextInt(); for(int i=0; i<l; i++) { int a = scan.nextInt()-1; int b = scan.nextInt()-1; long c = scan.nextLong(); for(int j=0; j<n; j++) { for(int k=0; k<n; k++) { long l1 = g[j][a]+c+g[b][k]; long l2 = g[j][b]+c+g[a][k]; long new_l = Math.min(l1,l2); long newll = Math.min(g[j][k],new_l); g[j][k] = newll; g[k][j] = newll; } } long ans = 0; for(int j=0; j<n; j++) { for(int k=j+1; k<n; k++) { ans += g[j][k]; } } System.out.println(ans); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
312f54c872376eb7221a563845224fa4
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
// package Practice1.CF25; import java.util.Scanner; public class CF025C { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); long[][] graph = new long[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { graph[i][j] = s.nextLong(); } } int k = s.nextInt(); for (int i = 0; i < k; i++) { int a = s.nextInt() - 1; int b = s.nextInt() - 1; long c = s.nextLong(); for (int j = 0; j < n; j++) { for (int m = 0; m < n; m++) { long ans1 = graph[j][a] + c + graph[b][m]; long ans2 = graph[j][b] + c + graph[a][m]; long ans3 = Math.min(ans1, ans2); long finalAns = Math.min(graph[j][m], ans3); graph[j][m] = finalAns; graph[m][j] = finalAns; } } long ans = 0; for (int j = 0; j < n; j++) { for (int m = j + 1; m < n; m++) { ans += graph[j][m]; } } System.out.println(ans); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 8
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
3f9b855bd32a56e7c2c95896e74cda96
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.*; public class P025C { private class Pair { private int i; private int j; private Pair(int i, int j) { this.i = Math.min(i, j); this.j = Math.max(i, j); } public int hashCode() { return 37 * i + j; } public boolean equals(Object other) { if (other instanceof Pair) { Pair otherPair = (Pair) other; return i == otherPair.i && j == otherPair.j; } return false; } } private int[][] distMatrix; private final int N; private Scanner sc = new Scanner(System.in); public P025C() { N = sc.nextInt(); distMatrix = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { distMatrix[i][j] = sc.nextInt(); } } } public void solve() { int k = sc.nextInt(); for (int i = 0; i < k; i++) { int a = sc.nextInt() - 1; int b = sc.nextInt() - 1; int c = sc.nextInt(); connect(a, b, c); System.out.printf("%d ", sum()); } System.out.println(); } private void update(int i, int j, int d_old, int d_new) { int d = Math.min(d_old, d_new); distMatrix[i][j] = distMatrix[j][i] = d; } private int dist(int i, int j) { return distMatrix[i][j]; } private void updateEntry(int i, int j, int k, int l) { int d = Math.min(dist(k, i) + dist(i, j) + dist(j, l), dist(k, j) + dist(j, i) + dist(i, l)); d = Math.min(d, dist(k, l)); update(k, l, dist(k, l), d); } private long sum() { long total = 0; for (int i = 0; i < N-1; i++) { for (int j = i+1; j < N; j++) { total += dist(i, j); } } return total; } private void connect(int a, int b, int c) { if (c >= dist(a, b)) return; update(a, b, dist(a, b), c); for (int i = 0; i < N-1; i++) { for (int j = i+1; j < N; j++) { updateEntry(a, b, i, j); } } } public static void main(String[] argv) { P025C solution = new P025C(); solution.solve(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
e631f2a597fd87c178bb461379465463
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private void eat(String line) { st = new StringTokenizer(line); } private String next() throws IOException { while(!st.hasMoreTokens()) { String line = in.readLine(); if(line == null) return null; eat(line); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); eat(""); go(); out.close(); } catch(Exception e) { e.printStackTrace(); System.exit(-1); } } public static void main(String[] args) { new Thread(new Main()).start(); } private long getSum(int n, int[][] d) { long result = 0; for(int i = 0; i < n; ++i) for(int j = i + 1; j < n; ++j) result += d[i][j]; return result; } private void update(int n, int[][] d, int a, int b, int c) { if(c >= d[a][b]) return; d[a][b] = d[b][a] = c; for(int i = 0; i < n; ++i) for(int j = i + 1; j < n; ++j) { int alpha = d[i][a] + d[a][b] + d[b][j]; int beta = d[i][b] + d[b][a] + d[a][j]; d[i][j] = d[j][i] = Math.min(d[i][j], Math.min(alpha, beta)); } } public void go() throws IOException { int n = nextInt(); int[][] d = new int[n][n]; for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) d[i][j] = nextInt(); int k = nextInt(); for(int i = 0; i < k; ++i) { int a = nextInt() - 1, b = nextInt() - 1, c = nextInt(); update(n, d, a, b, c); out.print(getSum(n, d)); if(i != k - 1) out.print(" "); } out.println(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
585f02ba03e9379d6bb2ddfc45a12760
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import static java.lang.Math.min; import java.util.Arrays; import java.util.Scanner; public class R025C { public void debug(Object... objects) { System.err.println(Arrays.deepToString(objects)); } public static final int INF = 987654321; public static final long LINF = 987654321987654321L; public static final double EPS = 1e-9; int n; int[][] d; int K; int a, b, c; public R025C() { } void warshallFloyd() { for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { d[i][j] = min(d[i][j], min(d[i][a] + c + d[b][j], d[i][b] + c + d[a][j])); } } } long calcSum() { long ans = 0L; for(int k=0; k<n; k++) { for(int j=k; j<n; j++) { ans += d[k][j]; } } return ans; } private void solve() { Scanner scanner = new Scanner(System.in); this.n = scanner.nextInt(); this.d = new int[n][n]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { d[i][j] = scanner.nextInt(); } } this.K = scanner.nextInt(); for(int i=0; i<K; i++) { this.a = scanner.nextInt() - 1; this.b = scanner.nextInt() - 1; this.c = scanner.nextInt(); d[a][b] = min(d[a][b], c); d[b][a] = min(d[b][a], c); warshallFloyd(); System.out.print(calcSum() + " "); } } public static void main(String[] args) { new R025C().solve(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
3f14278a862fe3c3871fc67be2a3df85
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class C { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); int[][] d = new int[n][n]; for (int i = 0; i < n; ++i) { String[] ss = br.readLine().split(" "); for (int j = 0; j < n; ++j) d[i][j] = Integer.parseInt(ss[j]); } int k = Integer.parseInt(br.readLine()); for (int t = 0; t < k; ++t) { if (t > 0) System.out.print(' '); String[] ss = br.readLine().split(" "); int u = Integer.parseInt(ss[0]); int v = Integer.parseInt(ss[1]); int w = Integer.parseInt(ss[2]); --u; --v; if (w < d[u][v]) { d[u][v] = d[v][u] = w; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) { d[i][j] = Math.min(d[i][j], d[i][u] + d[u][v] + d[v][j]); d[i][j] = Math.min(d[i][j], d[i][v] + d[v][u] + d[u][j]); } } long sum = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < i; ++j) sum += d[i][j]; System.out.print(sum); } System.out.println(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
9b8f8de273bc4498543c5b0599729704
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import static java.lang.Math.min; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Locale; import java.util.StringTokenizer; public class Main implements Runnable { void solve() throws IOException { int n = nextInt(); long[][] d = new long[n + 1][n + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { d[i][j] = nextLong(); } } int m = nextInt(); for (int ii = 0; ii < m; ii++) { int a = nextInt(); int b = nextInt(); int c = nextInt(); if (c < d[a][b]) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { long best = c + min(d[i][a] + d[b][j], d[i][b] + d[a][j]); d[i][j] = min(d[i][j], best); } } } long ans = 0; for (int i = 1; i <= n; i++) { for (int j = i + 1; j <= n; j++) { ans += d[i][j]; } } out.print(ans + " "); } out.println(); } private BufferedReader in; private PrintWriter out; private StringTokenizer st; private void eat(String str) { st = new StringTokenizer(str); } String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } eat(line); } 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()); } public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { new Main().run(); } }, "Main", 1 << 24).start(); } @Override public void run() { try { Locale.setDefault(Locale.US); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); eat(""); solve(); in.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
daa86be99e54066c882931f0e5de6bf7
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.*; import java.util.*; public class RoadsInBerland { public void solve() throws IOException { int n = nextInt(); long[][] d = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) d[i][j] = nextInt(); int k = nextInt(); for (int s = 0; s < k; s++) { int a = nextInt() - 1; int b = nextInt() - 1; long c = nextInt(); c = Math.min(c, d[a][b]); d[a][b] = c; d[b][a] = c; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (d[i][j] > d[i][a] + d[a][j]) { d[i][j] = d[i][a] + d[a][j]; d[j][i] = d[i][j]; } if (d[i][j] > d[i][b] + d[b][j]) { d[i][j] = d[i][b] + d[b][j]; d[j][i] = d[i][j]; } } long sum = 0; for (int u = 0; u < n; u++) for (int v = 0; v < u; v++) sum += d[u][v]; System.out.print(sum + " "); } } public static void main(String[] args) { new RoadsInBerland().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
be30fb09307ec7fd92d7605d3a860424
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.*; import java.io.*; public class CodeForces { static int[][] G; static StringBuilder sol; static long totalDist; public static void main(String[] args) throws Exception{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); sol = new StringBuilder(""); int N = Integer.parseInt(in.readLine()); G = new int[N][N]; for (int i = 0; i < N; i++) { StringTokenizer st = new StringTokenizer(in.readLine(), " "); for (int j = 0; j < N; j++) { G[i][j] = Integer.parseInt(st.nextToken()); totalDist += G[i][j]; } } totalDist = totalDist >> 1; int K = Integer.parseInt(in.readLine()); for (int i = 0; i < K; i++) { StringTokenizer st = new StringTokenizer(in.readLine(), " "); int beg = Integer.parseInt(st.nextToken()) - 1; int end = Integer.parseInt(st.nextToken()) - 1; int len = Integer.parseInt(st.nextToken()); findShortest(beg, end, len); } sol.deleteCharAt(sol.length() - 1); System.out.println(sol.toString()); //PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //out.close(); } public static void findShortest(int beg, int end, int len) { if (G[beg][end] <= len) { sol.append(totalDist + " "); return; } totalDist -= (G[beg][end] - len); G[beg][end] = len; G[end][beg] = len; for (int i = 0; i < G.length; i++) { for (int j = 0; j < G.length; j++) { totalDist -= G[i][j]; G[i][j] = Math.min(G[i][j], G[i][beg] + len + G[end][j]); G[j][i] = G[i][j]; totalDist += G[i][j]; } } sol.append(totalDist + " "); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
6b114d46451993d0650b2c733e562027
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.StreamTokenizer; public class C { public static void main(String[] args) throws Exception { new C().run(); } private StreamTokenizer st; private void run() throws Exception { st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); int n = nextInt(); int[][] w = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) w[i][j] = nextInt(); int k = nextInt(); for (int i = 0; i < k; i++) { int u = nextInt() - 1; int v = nextInt() - 1; int d = nextInt(); w[u][v] = Math.min(w[u][v], d); w[v][u] = Math.min(w[v][u], d); for (int x = 0; x < n; x++) for (int y = 0; y < n; y++) w[x][y] = Math.min(w[x][y], w[x][u] + w[u][v] + w[v][y]); for (int x = 0; x < n; x++) for (int y = 0; y < n; y++) w[x][y] = Math.min(w[x][y], w[x][v] + w[v][u] + w[u][y]); long s = 0; for (int x = 0; x < n; x++) for (int y = x + 1; y < n; y++) s += w[x][y]; System.out.print(s + " "); } } private int nextInt() throws Exception { st.nextToken(); return (int) st.nval; } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
1128f2590f719dabe526ddd5fa30b5f8
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); // 2-300 int[][] a = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { a[i][j] = scan.nextInt(); } } StringBuffer result = new StringBuffer(); for (int k = scan.nextInt(); k-- > 0;) { // 1-300 int x = scan.nextInt() - 1, y = scan.nextInt() - 1, z = scan .nextInt(); a[x][y] = a[y][x] = Math.min(a[x][y],z); for(int t:new int[]{x,y}){ for (int i = 0; i < n-1; i++) { for (int j = i+1; j < n; j++) { if(a[i][j] > a[i][t]+a[t][j]){ a[i][j] = a[j][i] = a[i][t]+a[t][j]; } } } } long sum = 0; for (int i = 0; i < n-1; i++) { for (int j = i+1; j < n; j++) { sum += a[i][j]; } } result.append(sum); result.append(" "); } System.out.println(result.replace(result.length()-1, result.length(), "")); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
11ecbc83e1b0bb96e3b10b8cf63a8f33
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; public class C { public static void main(String[] args) throws Exception { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); // 2-300 int[][] a = new int[n][n]; long sum = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { sum += (a[i][j] = scan.nextInt()); } } sum /= 2; StringBuffer result = new StringBuffer(); for (int k = scan.nextInt(); k-- > 0;) { // 1-300 int x = scan.nextInt() - 1, y = scan.nextInt() - 1, z = scan .nextInt(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { int value = a[i][x] + a[y][j] + z; if (a[i][j] > value) { sum -= a[i][j] - value; a[i][j] = a[j][i] = value; } } } result.append(sum); result.append(" "); } System.out.println(result.replace(result.length() - 1, result.length(), "")); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
d3cff499c25b9cc1a7c150359ff8cf25
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.*; public class c { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] graph = new int[n][n]; long sum = 0; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { graph[i][j] = in.nextInt(); if(i<j) sum += graph[i][j]; } } for(int k=in.nextInt(); k>0; k--) { int a = in.nextInt()-1; int b = in.nextInt()-1; int c = in.nextInt(); if(c >= graph[a][b]) { System.out.print(sum + " "); continue; } sum -= graph[a][b]; graph[b][a] = graph[a][b] = c; sum += graph[a][b]; for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { sum -= graph[i][j]; graph[j][i] = graph[i][j] = Math.min(graph[i][j],graph[i][a] + graph[a][b] + graph[b][j]); sum += graph[i][j]; } } System.out.print(sum + " "); continue; } System.out.println(); } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
4b5c060e4d1605e5f494d7d179c30f3c
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.*; import java.io.*; public class C { private static int[][] M; private static int n; public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); n = Integer.parseInt(in.readLine()); M = new int[n][n]; for (int i = 0; i < n; ++i) { String s = in.readLine(); String[] sp = s.split(" "); for (int j = 0; j < n; ++j) { M[i][j] = Integer.parseInt(sp[j]); } } int k = Integer.parseInt(in.readLine()); try { long[] ans = new long[k]; for (int i = 0; i < k; ++i) { String s = in.readLine(); ans[i] = new C().solve(s); } for (int i = 0; i < k; ++i) { System.out.print(ans[i]); if (i < k-1) System.out.print(" "); } System.out.println(); } catch (Exception e) { System.err.println(e); } } private long solve(String s) { String[] sp = s.split(" "); int u = Integer.parseInt(sp[0])-1; int v = Integer.parseInt(sp[1])-1; int d = Integer.parseInt(sp[2]); M[u][v] = Math.min(M[u][v], d); M[v][u] = M[u][v]; return Floyd_Warshall(u, v); } private long Floyd_Warshall(int u, int v) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { M[i][j] = Math.min(M[i][j], M[i][u]+M[u][v]+M[v][j]); M[i][j] = Math.min(M[i][j], M[i][v]+M[v][u]+M[u][j]); } } long ret = 0; for (int i = 0; i < n; ++i) for (int j = i+1; j < n; ++j) ret += M[i][j]; return ret; } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
30ca3eb00aa8fb9fed14ef27163604b8
train_002.jsonl
1280761200
There are n cities numbered from 1 to n in Berland. Some of them are connected by two-way roads. Each road has its own length — an integer number from 1 to 1000. It is known that from each city it is possible to get to any other city by existing roads. Also for each pair of cities it is known the shortest distance between them. Berland Government plans to build k new roads. For each of the planned road it is known its length, and what cities it will connect. To control the correctness of the construction of new roads, after the opening of another road Berland government wants to check the sum of the shortest distances between all pairs of cities. Help them — for a given matrix of shortest distances on the old roads and plans of all new roads, find out how the sum of the shortest distances between all pairs of cities changes after construction of each road.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long dist[][] = new long[n][n]; for ( int i = 0 ; i < n ; ++i ) { for ( int k = 0 ; k < n ; ++k ) { dist[i][k] = in.nextLong(); } } int t = in.nextInt(); for ( int w = 0 ; w < t ; ++w ) { int a = in.nextInt()-1; int b = in.nextInt()-1; long c = in.nextInt(); for ( int i = 0 ; i < n ; ++i ) { for ( int j = 0 ; j < n ; ++j ) { dist[i][j] = Math.min(dist[i][j],Math.min(dist[i][b]+dist[a][j]+c,dist[i][a]+dist[b][j]+c)); } } // print(dist); long sum = 0; for ( int i = 0 ; i < n ; ++i ) { for ( int j = i+1 ; j < n ; ++j ) { sum += dist[i][j]; } } System.out.println(sum); } } private static void print(int[][] dist) { for ( int i = 0 ; i < dist.length ; ++i ) { for ( int j = 0 ; j < dist.length ; ++j ) { System.out.print(dist[i][j]+" "); } System.out.println(); } } }
Java
["2\n0 5\n5 0\n1\n1 2 3", "3\n0 4 5\n4 0 9\n5 9 0\n2\n2 3 8\n1 2 1"]
2 seconds
["3", "17 12"]
null
Java 6
standard input
[ "shortest paths", "graphs" ]
5dbf91f756fecb004c836a628eb23578
The first line contains integer n (2 ≤ n ≤ 300) — amount of cities in Berland. Then there follow n lines with n integer numbers each — the matrix of shortest distances. j-th integer in the i-th row — di, j, the shortest distance between cities i and j. It is guaranteed that di, i = 0, di, j = dj, i, and a given matrix is a matrix of shortest distances for some set of two-way roads with integer lengths from 1 to 1000, such that from each city it is possible to get to any other city using these roads. Next line contains integer k (1 ≤ k ≤ 300) — amount of planned roads. Following k lines contain the description of the planned roads. Each road is described by three space-separated integers ai, bi, ci (1 ≤ ai, bi ≤ n, ai ≠ bi, 1 ≤ ci ≤ 1000) — ai and bi — pair of cities, which the road connects, ci — the length of the road. It can be several roads between a pair of cities, but no road connects the city with itself.
1,900
Output k space-separated integers qi (1 ≤ i ≤ k). qi should be equal to the sum of shortest distances between all pairs of cities after the construction of roads with indexes from 1 to i. Roads are numbered from 1 in the input order. Each pair of cities should be taken into account in the sum exactly once, i. e. we count unordered pairs.
standard output
PASSED
041d1227db29c78a56a55dfdeec6b899
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.*; public class JavaApplication168<T> { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long k = sc.nextLong(); if(n == 1){ System.out.println(0); return; } long a[] = new long[n]; for(int i=0; i<n; i++){ a[i] = sc.nextLong(); } long rest = a[0] % k; long min = a[0]; for (int i = 1; i < n; i++) { min = Math.min(min, a[i]); if (a[i] % k != rest) { System.out.println(-1); return; } } long result = 0; for (int i = 0; i < n; i++) { result += (a[i] - min) / k; } System.out.println(result); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
1cf051713e8f36df9ffa4fdc845496ca
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); long[] data = new long[input.nextInt()]; long n = input.nextInt(); for (int i = 0; i < data.length; i++) { data[i] = input.nextLong(); } long count = 0; long x; long fuck = 1; for (int i = 0; i < data.length-1; i++) { if (data [i] % n != data[i+1] % n) { count = -1; break; } else { if (data[i] > data[i+1]) { count = count + fuck * ((data [i] - data [i+1]) /n); fuck++; }else if(data [i] < data [i+1]){ count = count + ((data [i+1] - data [i]) /n ); fuck++; data [i+1] = data [i]; }else if(data [i] == data [i+1]){ fuck++; } } } System.out.println (count); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
25aea424642f7a268b6ca61835544f9e
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner(System.in); long[] data = new long[input.nextInt()]; long n = input.nextInt(); for (int i = 0; i < data.length; i++) { data[i] = input.nextLong(); } long count = 0; long fuck = 1; for (int i = 0; i < data.length-1; i++) { if (data [i] % n != data[i+1] % n) { count = -1; break; } else { if (data[i] > data[i+1]) { count = count + fuck * ((data [i] - data [i+1]) /n); fuck++; }else if(data [i] < data [i+1]){ count = count + ((data [i+1] - data [i]) /n ); fuck++; data [i+1] = data [i]; }else if(data [i] == data [i+1]){ fuck++; } } } // Arrays.sort(data); // for (int i = 1; i < data.length; i++) { // if(data [0] % n != data [i] % n){ // count = -1; // break; // }else{ // if(data [i] != data [0]){ // count = count + (data [i] -data [0])/n; // } // } // } System.out.println (count); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
678b4b7876ee437d55b7e1e06e365bd2
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.*; import java.io.*; public class A { static final boolean stdin = true; static final String filename = ""; static FastScanner br; static PrintWriter pw; public static void main(String[] args) throws IOException { if (stdin) { br = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); } else { br = new FastScanner(filename + ".in"); pw = new PrintWriter(new FileWriter(filename + ".out")); } Solver solver = new Solver(); solver.solve(br, pw); pw.close(); } static class Solver { static long mod = (long) (1e9); public void solve(FastScanner br, PrintWriter pw) throws IOException { int n = br.ni(); long k = br.ni(); long[] in = br.nla(n); long min = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { min = Math.min(min, in[i]); } for (int i = 0; i < n; i++) { in[i] -= min; } boolean works = true; long sum = 0; for (int i = 0; i < n; i++) { if (in[i] % k == 0) { sum += in[i] / k; } else { works = false; } } if (works) pw.println(sum); else pw.println(-1); } static long gcd(long a, long b) { if (a > b) return gcd(b, a); if (a == 0) return b; return gcd(b % a, a); } static long lcm(long a, long b) { return a * (b / gcd(a, b)); } static long pow(long a, long b) { if (b == 0) return 1L; long val = pow(a, b / 2); if (b % 2 == 0) return val * val % mod; else return val * val % mod * a % mod; } } static class Point implements Comparable<Point> { int a; int b; Point(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(Point o) { return this.a - o.a; } public boolean equals(Object obj) { if (obj instanceof Point) { Point other = (Point) obj; return a == other.a && b == other.b; } return false; } public int hashCode() { return 65536 * a + b + 4733 * 0; } } 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)); } ArrayList<Integer>[] ng(int n, int e) { ArrayList<Integer>[] adj = new ArrayList[n]; for (int i = 0; i < n; i++) { adj[i] = new ArrayList<Integer>(); } for (int i = 0; i < e; i++) { int a = ni() - 1; int b = ni() - 1; adj[a].add(b); adj[b].add(a); } return adj; } Integer[] nIa(int n) { Integer[] arr = new Integer[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } int[] nia(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = ni(); } return arr; } Long[] nLa(int n) { Long[] arr = new Long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } long[] nla(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nl(); } return arr; } String[] nsa(int n) { String[] arr = new String[n]; for (int i = 0; i < n; i++) { arr[i] = nt(); } return arr; } String nt() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(nt()); } long nl() { return Long.parseLong(nt()); } double nd() { return Double.parseDouble(nt()); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
b4755523a21a867cf51e23e36ea8ce54
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Question793A { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); long k=sc.nextLong(); int[] arr=new int[n]; int min=Integer.MAX_VALUE; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); min=Math.min(min,arr[i]); } //System.out.println(min); long totaldistance=0; for(int i=0;i<arr.length;i++){ totaldistance=totaldistance+arr[i]-min; if(totaldistance%k!=0){ System.out.println("-1"); return; } } System.out.println(totaldistance/k); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
18c0ae028f6bdf33ee480a815d686033
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.*; public class Solution { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); int x=sc.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } int min=Integer.MAX_VALUE; int k=0; for(int i=0;i<n;i++) { if(a[i]<min) { min=a[i]; k=i; } } //System.out.println(k); long sum=0; int w=0; for(int i=0;i<n;i++) { if(i!=k){ int z=a[i]-a[k]; //System.out.println(z); //System.out.println(z%x); if(z%x==0) { sum=sum+z/x; // System.out.println(z/x); //System.out.println(sum); } else { w=1; break; } } } if(w==1) System.out.println("-1"); else System.out.println(sum); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
abe951a42b3deae257ee56c3fa7c9af8
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author SteinOr */ public class Oleg_And_Shares_793A { public static void main(String[] args){ Scanner input = new Scanner(System.in); long n = input.nextInt(); long k = input.nextInt(); long s = 0; long low = input.nextInt(); long mod = low % k; for (long i = 1; i < n; i++){ long curr = input.nextInt(); if(curr % k != mod){ System.out.println(-1); return; } if(curr >= low){ s += (curr - low) / k; }else{ s += (low - curr) / k * i; low = curr; } } System.out.println(s); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
5368094b3652fdfd6a5f68b5f26202b0
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; public class A_OlegAndShares { public static void main(String[] args) { Scanner s=new Scanner (System.in); //************************** Var ****************** int n,k; n=s.nextInt(); k=s.nextInt(); long a[]=new long[n]; long min=100000000000L,p,sec=0; //************************** Input **************************** for (int i = 0; i < n; i++) a[i]=s.nextLong(); //************************** Sort **************************** for(int i=0;i<n;i++){ if(min>a[i]) min=a[i]; } //************************** Process **************************** for (int i = 0; i < n; i++) { if(min!=a[i]){ p=a[i]-min; if(p < k) { sec=-1; i=n; } else if(p%k!=0) { sec=-1; i=n; } else sec+=(p/k); }} //************************** Out ******************************* System.out.println(sec); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
8ea17d3ec0bc9e9957ce3610df8ca7cc
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.PriorityQueue; import java.util.Set; import java.util.StringTokenizer; public class Code { public static void main(String[] args) { // Use the Scanner class MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int n = sc.nextInt(); int k = sc.nextInt(); int[] A = new int[n]; for (int i = 0; i < n; ++i) { A[i] = sc.nextInt(); } int min_price = Arrays.stream(A).min().getAsInt(); long time = 0; for (int i = 0; i < n; ++i) { int delta_i = A[i] - min_price; if (delta_i % k != 0) { System.out.println(-1); return; } int ti = delta_i / k; time += ti; } System.out.println(time); } static long price_per_n(long n, Map<Character,Integer> M, int nb, int ns, int nc, int pb, int ps, int pc) { long p1 = n * M.getOrDefault('B', 0) - nb; p1 *= pb; long p2 = n * M.getOrDefault('S', 0) - ns; p2 *= ps; long p3 = n * M.getOrDefault('C', 0) - nc; p3 *= pc; return Math.max(p1, 0) + Math.max(p2, 0) + Math.max(p3, 0); } static class Item implements Comparable<Item> { char key; int n_required; int n_units_available; int n_sandwiches; int unit_price; public Item(char key, int n_required, int n_units_available, int unit_price) { this.key = key; this.n_required = n_required; this.n_units_available = n_units_available; this.unit_price = unit_price; n_sandwiches = n_units_available / n_required; } @Override public int hashCode() { return Character.hashCode(key); } @Override public boolean equals(Object obj) { Item other = (Item) obj; return this.key == other.key; } @Override public int compareTo(Item o) { return Integer.compare(this.n_sandwiches, o.n_sandwiches); } } static boolean are_last_4_equal(String s, int i, char val) { return (s.charAt(i-1) == val && s.charAt(i-2) == val && s.charAt(i-3) == val && s.charAt(i-4) == val); } 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
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
3f4a4ffdd982dd36bd226ec7444c95a1
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner scn = new Scanner(System.in); int n = scn.nextInt(); long k = scn.nextInt(); int[] mas = new int[n]; long c = 0; ArrayList<Integer> j = new ArrayList<>(); for(int i = 0;i<n;i++){ j.add(scn.nextInt()); } long d = Collections.min(j); long g = 0; long ans = 0; for(int i = 0;i<n;i++){ g =j.get(i)-d; if(g%k!=0){ ans = -1; break; } else { ans+=g/k; } } System.out.println(ans); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
5a2b267af0d440994fd9eb3a435bbbd4
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; public class main { public static void main(String[] args){ Scanner in =new Scanner(System.in); int x=in.nextInt(); int y=in.nextInt(); int[] s=new int[x]; int n,l=1000000000,r=0; long m=0; for(n=0;n<x;n++){ s[n]=in.nextInt(); l=Math.min(l,s[n]); } for(n=0;n<x;n++){ if((s[n]-l)%y==0){ m+=(s[n]-l)/y; } else{ r=1; System.out.println(-1); break; } } if(r==0){ System.out.println(m); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
2b7f88a570cdcfd608247ead6719abed
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.Scanner; public class oas { public static void main(String args[]) { Scanner s= new Scanner(System.in); int n=s.nextInt(); int r=0,i; long add=0; int k=s.nextInt(); int a[]=new int[n]; a[0]=s.nextInt(); int temp=a[0]; if(n==1) System.out.print(0); else { for( i=1; i<n; i++) { a[i]=s.nextInt(); if(temp>a[i]) temp=a[i]; } for(i=0; i<n; i++) { if( (a[i]-temp)%k!=0) {r=1; break;} add=add+(a[i]-temp); } if(r==1) System.out.print(-1); else System.out.print(add/k); }} }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
e476a8410657989626969c20f4b63702
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.BufferedReader; import java.io.PrintWriter; import java.io.InputStreamReader; import java.io.IOException; import java.util.StringTokenizer; public class Main { static Scanner in = new Scanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException { long t = 0, n = in.nextLong(), k = in.nextLong(), min = in.nextLong(), m = min % k; for(int i = 1; i < n; i++) { long a = in.nextLong(); if(a % k != m) { out.print(-1); out.close(); return; } if(a > min) t += a - min; else { t += (min - a) * i; min = a; } } out.print(t / k); out.close(); } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } public String next() throws IOException { if(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { if(!st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); String r = st.nextToken("\n"); st = new StringTokenizer(br.readLine(), " "); return r; } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
722b799fba75b46d268b97190a0e8690
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Scanner; public class Main { static int a[]=new int[100010]; public static void main(String[] args) { int n,k,i,min=1000000010; BigInteger ans=BigInteger.valueOf(0); Scanner in = new Scanner(System.in); n=in.nextInt(); k=in.nextInt(); for(i=0;i<n;i++) { a[i]=in.nextInt(); if(a[i]<min) min=a[i]; } boolean flag=true; for(i=0;i<n;i++) { if(a[i]==min) continue; if((a[i]-min)%k>0) { flag=false; break; } else ans=ans.add(BigInteger.valueOf((a[i]-min)/k)); } if(flag) System.out.println(ans); else System.out.println("-1"); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
662475b4412ac00d52a10c4a82846ccd
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.*; import java.util.*; public class OlegAndShares{ public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] vals = br.readLine().split(" "); int n = Integer.parseInt(vals[0]); int k = Integer.parseInt(vals[1]); int min = Integer.MAX_VALUE; long cnt = 0; int[] shares = new int[n]; vals = br.readLine().split(" "); if(n==1){ System.out.println(0); return; } for(int i=0;i<n;i++){ shares[i] = Integer.parseInt(vals[i]); min = Math.min(min,shares[i]); } for(int i=0;i<n;i++){ if(shares[i]!=min){ int temp = shares[i] - min; if(temp%k==0) cnt+=(temp/k); else{ k = 0; break; } } } System.out.println(k!=0?cnt:-1); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
dd71c1527c59c43d4f90c607b1ff4356
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { int N, dec; Reader sc = new Reader(); N = sc.nextInt(); dec = sc.nextInt(); Integer input[] = new Integer[N]; for (int i = 0; i < N; i++) { input[i] = sc.nextInt(); } System.out.println(minSecsEq(input, dec)); sc.close(); } private static long minSecsEq(Integer[] input, int dec) { long resp = 0; if (input.length == 1) { return 0; } Arrays.sort(input); if (dec == 1) { for (int i = 1; i < input.length; i++) { resp += input[i] - input[0]; } } else { for (int i = 1; i < input.length; i++) { int r = (input[i]-input[0])/dec; int q = (input[i]-input[0])%dec; if (q != 0) { return -1; } resp += (input[i] - input[0]) / dec; } } return resp; } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
1e91fedf4033165fcdf136ac4961383e
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Arrays; public final class CF_Tinkoff_Shares{ static void log(int[] X){ int L=X.length; for (int i=0;i<L;i++){ logWln(X[i]+" "); } log(""); } static void log(long[] X){ int L=X.length; for (int i=0;i<L;i++){ logWln(X[i]+" "); } log(""); } static void log(Object[] X){ int L=X.length; for (int i=0;i<L;i++){ logWln(X[i]+" "); } log(""); } static void log(Object o){ logWln(o+"\n"); } static void logWln(Object o){ System.err.print(o); // outputWln(o); } static void info(Object o){ System.out.println(o); //output(o); } static void output(Object o){ outputWln(""+o+"\n"); } static void outputWln(Object o){ // System.out.print(o); try { out.write(""+ o); } catch (Exception e) { } } static int pgcd(int a,int b){ if (a<b) return pgcd(b,a); while (b!=0){ int c=b; b=a%b; a=c; } return a; } // Global vars static BufferedWriter out; static InputReader reader; static long MOD=1000000007; static void process() throws Exception { out = new BufferedWriter(new OutputStreamWriter(System.out)); reader=new InputReader(System.in); long n=reader.readInt(); int k=reader.readInt(); int mod=-1; boolean ok=true; long min=Integer.MAX_VALUE; long sum=0; long cnt=0; for (int i=0;i<n;i++){ int a=reader.readInt(); if (mod==-1) mod=a%k; else { if (mod!=a%k) ok=false; } sum+=a/k; if (a<min) { min=a; cnt=1; } else if (a==min) cnt++; } sum-=(min/k)*n; if (ok){ output(sum); } else output(-1); try { out.close(); } catch (Exception e){} } public static void main(String[] args) throws Exception { process(); } static final class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } private int read() throws IOException { if (curChar >= numChars) { curChar = 0; numChars = stream.read(buf); if (numChars <= 0) { return -1; } } return buf[curChar++]; } public final String readString() throws IOException { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res=new StringBuilder(); do { res.append((char)c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public final int readInt() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } public final long readLong() throws IOException { int c = read(); boolean neg=false; while (isSpaceChar(c)) { c = read(); } char d=(char)c; //log("d:"+d); if (d=='-') { neg=true; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); //log("res:"+res); if (neg) return -res; return res; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
3e06d1e8dd892547b5928cccbf0c7378
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import javafx.util.Pair; import static java.lang.Double.parseDouble; import static java.lang.Integer.max; import static java.lang.Integer.min; import static java.lang.Integer.parseInt; import static java.lang.Long.parseLong; import static java.lang.StrictMath.abs; import static java.lang.System.exit; import static java.util.Arrays.sort; import java.awt.*; import java.io.*; import java.util.*; public class A { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; public final static long MOD1 = (long) (1e9 + 7); public final static long MOD2 = (long) (1e9 + 9); static void solve() throws Exception { int n = nextInt(), k = nextInt(), mn = 1000000000; long ans=0; int a[] = new int[n]; for(int i=0;i<n;i++) { a[i] = nextInt(); mn = min(mn,a[i]); } for(int i=0;i<n;i++) { if((a[i] - mn) % k != 0) { out.print(-1); return; } else { ans += (a[i] - mn) / k; } } out.print(ans); } static class HashString { public long MOD; long[] power; Long hashedString; String s; public HashString(String s,Long MOD) { this.s = s; this.MOD = MOD; power = new long[s.length() + 10]; FillArrays(); this.hashedString = hash(s); } public Long getHash() { return this.hashedString; } private void FillArrays() { power[0] = 1; for (int i = 1; i < power.length; i++) power[i] = (power[i - 1] * 5) % MOD; } public long hash(String str) { long pow1 = 0; for (int i = 0; i < str.length(); i++) pow1 += ((str.charAt(i) - 'a' + 1) * power[i]) % MOD; return pow1; } public void replaceChar(int i,char c) { hashedString -= ((s.charAt(i) - 'a' + 1) * power[i]) % MOD; hashedString += ((c - 'a' + 1) * power[i]) % MOD; } } static String replace(String s,Character c,int i) { StringBuilder tmp = new StringBuilder(s); tmp.setCharAt(i, c); return tmp.toString(); } static int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); } static int nextInt() throws IOException { return parseInt(next()); } static long nextLong() throws IOException { return parseLong(next()); } static double nextDouble() throws IOException { return parseDouble(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } public static void main(String[] args) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); long lStartTime = System.currentTimeMillis(); solve(); long lEndTime = System.currentTimeMillis(); //System.out.println("Elapsed time in seconds: " + (double)(lEndTime - lStartTime) / 1000.0); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); exit(1); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
9ec4d9dde2615395e11df27b0639b361
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner ob= new Scanner(System.in); int n=ob.nextInt(); int k= ob.nextInt(); long a[]= new long[n]; long s=0; long min=Integer.MAX_VALUE; for(int i=0; i<n; i++) { a[i]=ob.nextInt(); if(a[i]<min) { min=a[i]; } } int f=0; for(int i=0; i<n; i++) { if((a[i]-min)%k!=0) { f=1; } else { s+= (a[i]-min)/k; } } if(f==1) System.out.println(-1); else System.out.println(s); } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output
PASSED
cd60806ab2ad2fb1175b3aa8fda9f716
train_002.jsonl
1492965900
Oleg the bank client checks share prices every day. There are n share prices he is interested in. Today he observed that each second exactly one of these prices decreases by k rubles (note that each second exactly one price changes, but at different seconds different prices can change). Prices can become negative. Oleg found this process interesting, and he asked Igor the financial analyst, what is the minimum time needed for all n prices to become equal, or it is impossible at all? Igor is busy right now, so he asked you to help Oleg. Can you answer this question?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.PrintStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Wolfgang Beyer */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long k = in.nextInt(); if (n == 1) { out.println(0); return; } long[] a = in.readLongArray(n); long rest = a[0] % k; long min = a[0]; for (int i = 1; i < n; i++) { min = Math.min(min, a[i]); if (a[i] % k != rest) { out.println(-1); return; } } long result = 0; for (int i = 0; i < n; i++) { result += (a[i] - min) / k; } out.println(result); } } static class InputReader { private static BufferedReader in; private static StringTokenizer tok; public InputReader(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public long[] readLongArray(int n) { long[] ar = new long[n]; for (int i = 0; i < n; i++) { ar[i] = nextLong(); } return ar; } public String next() { try { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); //tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter } } catch (IOException ex) { System.err.println("An IOException was caught :" + ex.getMessage()); } return tok.nextToken(); } } }
Java
["3 3\n12 9 15", "2 2\n10 9", "4 1\n1 1000000000 1000000000 1000000000"]
1 second
["3", "-1", "2999999997"]
NoteConsider the first example. Suppose the third price decreases in the first second and become equal 12 rubles, then the first price decreases and becomes equal 9 rubles, and in the third second the third price decreases again and becomes equal 9 rubles. In this case all prices become equal 9 rubles in 3 seconds.There could be other possibilities, but this minimizes the time needed for all prices to become equal. Thus the answer is 3.In the second example we can notice that parity of first and second price is different and never changes within described process. Thus prices never can become equal.In the third example following scenario can take place: firstly, the second price drops, then the third price, and then fourth price. It happens 999999999 times, and, since in one second only one price can drop, the whole process takes 999999999 * 3 = 2999999997 seconds. We can note that this is the minimum possible time.
Java 8
standard input
[ "implementation", "math" ]
9e71b4117a24b906dbc16e6a6d110f50
The first line contains two integers n and k (1 ≤ n ≤ 105, 1 ≤ k ≤ 109) — the number of share prices, and the amount of rubles some price decreases each second. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — the initial prices.
900
Print the only line containing the minimum number of seconds needed for prices to become equal, of «-1» if it is impossible.
standard output