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
f4287f4b1445d66a00aabbc6b7e7d74a
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; import java.math.BigInteger; /** __ __ ( _) ( _) / / \\ / /\_\_ / / \\ / / | \ \ / / \\ / / |\ \ \ / / , \ , / / /| \ \ / / |\_ /| / / / \ \_\ / / |\/ _ '_| \ / / / \ \\ | / |/ 0 \0\ / | | \ \\ | |\| \_\_ / / | \ \\ | | |/ \.\ o\o) / \ | \\ \ | /\\`v-v / | | \\ | \/ /_| \\_| / | | \ \\ | | /__/_ `-` / _____ | | \ \\ \| [__] \_/ |_________ \ | \ () / [___] ( \ \ |\ | | // | [___] |\| \| / |/ /| [____] \ |/\ / / || ( \ [____ / ) _\ \ \ \| | || \ \ [_____| / / __/ \ / / // | \ [_____/ / / \ | \/ // | / '----| /=\____ _/ | / // __ / / | / ___/ _/\ \ | || (/-(/-\) / \ (/\/\)/ | / | / (/\/\) / / // _________/ / / \____________/ ( @author NTUDragons-Reborn */ public class Solution{ 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(); } // main solver static class Task{ double eps= 0.00000001; static final int MAXN = 100005; static final int MOD= 1000000007; // stores smallest prime factor for every number static int spf[] = new int[MAXN]; static boolean[] prime; Map<Integer,Set<Integer>> dp= new HashMap<>(); // Calculating SPF (Smallest Prime Factor) for every // number till MAXN. // Time Complexity : O(nloglogn) public void sieve() { spf[1] = 1; for (int i=2; i<MAXN; i++) // marking smallest prime factor for every // number to be itself. spf[i] = i; // separately marking spf for every even // number as 2 for (int i=4; i<MAXN; i+=2) spf[i] = 2; for (int i=3; i*i<MAXN; i++) { // checking if i is prime if (spf[i] == i) { // marking SPF for all numbers divisible by i for (int j=i*i; j<MAXN; j+=i) // marking spf[j] if it is not // previously marked if (spf[j]==j) spf[j] = i; } } } void 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[n + 1]; for (int i = 0; i <= n; i++) prime[i] = true; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, then it is a // prime if (prime[p] == true) { // Update all multiples of p for (int i = p * p; i <= n; i += p) prime[i] = false; } } } // A O(log n) function returning primefactorization // by dividing by smallest prime factor at every step public Set<Integer> getFactorization(int x) { if(dp.containsKey(x)) return dp.get(x); Set<Integer> ret = new HashSet<>(); while (x != 1) { if(spf[x]!=2) ret.add(spf[x]); x = x / spf[x]; } dp.put(x,ret); return ret; } // function to find first index >= x public int lowerIndex(List<Integer> arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) >= x) h = mid - 1; else l = mid + 1; } return l; } public int lowerIndex(int[] arr, int n, int x) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] >= x) h = mid - 1; else l = mid + 1; } return l; } // function to find last index <= y public int upperIndex(List<Integer> arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr.get(mid) <= y) l = mid + 1; else h = mid - 1; } return h; } public int upperIndex(int[] arr, int n, int y) { int l = 0, h = n - 1; while (l <= h) { int mid = (l + h) / 2; if (arr[mid] <= y) l = mid + 1; else h = mid - 1; } return h; } // function to count elements within given range public int countInRange(List<Integer> arr, int n, int x, int y) { // initialize result int count = 0; count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1; return count; } public int _gcd(int a, int b) { if(b == 0) { return a; } else { return _gcd(b, a % b); } } public int add(int a, int b){ a+=b; if(a>=MOD) a-=MOD; else if(a<0) a+=MOD; return a; } public int mul(int a, int b){ long res= (long)a*(long)b; return (int)(res%MOD); } public int power(int a, int b) { int ans=1; while(b>0){ if((b&1)!=0) ans= mul(ans,a); b>>=1; a= mul(a,a); } return ans; } int[] fact= new int[MAXN]; int[] inv= new int[MAXN]; public int Ckn(int n, int k){ if(k<0 || n<0) return 0; return mul(mul(fact[n],inv[k]),inv[n-k]); } public int inverse(int a){ return power(a,MOD-2); } public void preprocess() { fact[0]=1; for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i); inv[MAXN-1]= inverse(fact[MAXN-1]); for(int i=MAXN-2;i>=0;i--){ inv[i]= mul(inv[i+1],i+1); } } /** * return VALUE of lower bound for unsorted array */ public int lowerBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.lower(x); } /** * return VALUE of upper bound for unsorted array */ public int upperBoundNormalArray(int[] arr, int x){ TreeSet<Integer> set= new TreeSet<>(); for(int num: arr) set.add(num); return set.higher(x); } public void debugArr(int[] arr){ for(int i: arr) out.print(i+" "); out.println(); } InputReader in; PrintWriter out; public void solve(InputReader in, PrintWriter out) { this.in=in; this.out=out; int t= in.nextInt(); while(t-->0){ solveC(); } } public void solveB(){ int n= in.nextInt(); if(n%2==0) { for(int i=2;i<=n;i+=2) out.print(i+" "+(i-1)+" "); out.println(); } else{ for(int i=2;i<=n-3;i+=2){ out.print(i+" "+(i-1)+" "); } out.print((n-1)+" "+n+" "+(n-2)); out.println(); } } public void solveA(){ int n=in.nextInt(); int[] a= in.nextIntArr(n); } public void solveC(){ int n= in.nextInt(); int[] d= in.nextIntArr(n); Arrays.sort(d); int[] dif= new int[n-1]; long sum=0; for(int i=0;i<n-1;i++) dif[i]= d[i+1]-d[i]; for(int i: dif) sum+= i; sum-= SubArraySum(dif,n-1); out.println(sum); } //function compute sum all sub-array public static long SubArraySum( int arr[] , int n ) { long result = 0; // computing sum of subarray using formula for (int i=0; i<n; i++) result += ((long)arr[i] * (long)(i+1) * (n-i)); // return all subarray sum return result ; } public void solveE(){ } } static class Venice{ public Map<Long,Long> m= new HashMap<>(); public long base=0; public long totalValue=0; private int M= 1000000007; private long addMod(long a, long b){ a+=b; if(a>=M) a-=M; return a; } public void reset(){ m= new HashMap<>(); base=0; totalValue=0; } public void update(long add){ base= base+ add; } public void add(long key, long val){ long newKey= key-base; m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val)); } } static class Tuple implements Comparable<Tuple>{ int x, y, z; public Tuple(int x, int y, int z){ this.x= x; this.y= y; this.z=z; } @Override public int compareTo(Tuple o){ return this.x-o.x; } } static class Pair implements Comparable<Pair>{ public int x; public int y; public Pair(int x, int y){ this.x= x; this.y= y; } @Override public int compareTo(Pair o) { return this.x-o.x; } } // public static class compareL implements Comparator<Tuple>{ // @Override // public int compare(Tuple t1, Tuple t2) { // return t2.l - t1.l; // } // } // fast input reader class; static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream stream) { br = new BufferedReader(new InputStreamReader(stream)); } public String nextToken() { while (st == null || !st.hasMoreTokens()) { String line = null; try { line = br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } if (line == null) { return null; } st = new StringTokenizer(line); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public double nextDouble(){ return Double.parseDouble(nextToken()); } public long nextLong(){ return Long.parseLong(nextToken()); } public int[] nextIntArr(int n){ int[] arr= new int[n]; for(int i=0;i<n;i++) arr[i]= nextInt(); return arr; } public long[] nextLongArr(int n){ long[] arr= new long[n]; for(int i=0;i<n;i++) arr[i]= nextLong(); return arr; } public List<Integer> nextIntList(int n){ List<Integer> arr= new ArrayList<>(); for(int i=0;i<n;i++) arr.add(nextInt()); return arr; } public int[][] nextIntMatArr(int n, int m){ int[][] mat= new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt(); return mat; } public List<List<Integer>> nextIntMatList(int n, int m){ List<List<Integer>> mat= new ArrayList<>(); for(int i=0;i<n;i++){ List<Integer> temp= new ArrayList<>(); for(int j=0;j<m;j++) temp.add(nextInt()); mat.add(temp); } return mat; } public char[] nextStringCharArr(){ return nextToken().toCharArray(); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
fd7a7bc2b396708f21d97ea645f9d956
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.io.*; import java.util.*; import java.text.DecimalFormat; import java.math.*; public class Main { static int mod = 1000000007; /*****************code By Priyanshu *******************************************/ 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; } } // this > other return +ve // this < other return -ve // this == other return 0 public static class Pair implements Comparable<Pair> { int st; int et; public Pair(int st, int et) { this.st = st; this.et = et; } public int compareTo(Pair other) { if (this.st != other.st) { return this.st - other.st; } else { return this.et - other.et; } } } static long fastPower(long a, long b, int n) { long res = 1; while ( b > 0) { if ( (b&1) != 0) { res = (res * a % n) % n; } a = (a % n * a % n) % n; b = b >> 1; } return res; } // function to find // the rightmost set bit static int PositionRightmostSetbit(int n) { // Position variable initialize // with 1 m variable is used to // check the set bit int position = 1; int m = 1; while ((n & m) == 0) { // left shift m = m << 1; position++; } return position; } // used for swapping ith and jth elements of array // public static void swap(int[] arr, int i, int j) { // int temp = arr[i]; // arr[i] = arr[j]; // arr[j] = temp; // } public static void swap(long i, long j) { long temp = i; i = j; j = temp; } static boolean palindrome(String s) { return new StringBuilder(s).reverse().toString().equals(s); } static boolean isPerfectSquare(double x) { double sr = Math.sqrt(x); return ((sr * sr) == x); } public static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static int nod(long l) { if(l>=1000000000000000000l) return 19; if(l>=100000000000000000l) return 18; if(l>=10000000000000000l) return 17; if(l>=1000000000000000l) return 16; if(l>=100000000000000l) return 15; if(l>=10000000000000l) return 14; if(l>=1000000000000l) return 13; if(l>=100000000000l) return 12; if(l>=10000000000l) return 11; if(l>=1000000000) return 10; if(l>=100000000) return 9; if(l>=10000000) return 8; if(l>=1000000) return 7; if(l>=100000) return 6; if(l>=10000) return 5; if(l>=1000) return 4; if(l>=100) return 3; if(l>=10) return 2; return 1; } //Arrays.sort(a,(c,d) -> Integer.compare(c[0],d[0])); public static boolean areAllBitsSet(int n ) { // all bits are not set if (n == 0) return false; // if true, then all bits are set if (((n + 1) & n) == 0) return true; // else all bits are not set return false; } public static long[] sort(long[] arr) { List<Long> temp = new ArrayList(); for (long i : arr) temp.add(i); Collections.sort(temp); int start = 0; for (long i : temp) arr[start++] = i; return arr; } public static int[] radixSort2(int[] a) { int n = a.length; int[] c0 = new int[0x101]; int[] c1 = new int[0x101]; int[] c2 = new int[0x101]; int[] c3 = new int[0x101]; for(int v : a) { c0[(v&0xff)+1]++; c1[(v>>>8&0xff)+1]++; c2[(v>>>16&0xff)+1]++; c3[(v>>>24^0x80)+1]++; } for(int i = 0;i < 0xff;i++) { c0[i+1] += c0[i]; c1[i+1] += c1[i]; c2[i+1] += c2[i]; c3[i+1] += c3[i]; } int[] t = new int[n]; for(int v : a)t[c0[v&0xff]++] = v; for(int v : t)a[c1[v>>>8&0xff]++] = v; for(int v : a)t[c2[v>>>16&0xff]++] = v; for(int v : t)a[c3[v>>>24^0x80]++] = v; return a; } public static int fun2(int a[], int aa[],int n){ int count = 0; for(int i=3;i<2*n;i++){ for(int j=1;j<=Math.sqrt(i);j++){ if(i%j==0 && i!=j*j){ if(aa[j]+aa[i/j]==i){ count++; } } } } return count; } public static long fun1(long a[], int n,long ans , long add) { for (int i = 2;i<n ;i++ ) { add = add +a[i-2]; ans = ans - (a[i]*(i-1)); ans = ans + add; } int b[] = new int[5]; radixSort2(b); return ans; } public static void main( String[] args) { try { System.setIn(new FileInputStream("input.txt")); System.setOut(new PrintStream(new FileOutputStream("output.txt"))); } catch (Exception e) { System.err.println("Error"); } FastReader sc = new FastReader(); int t = Integer.parseInt(sc.next()); // int t = 1; while(t-->0){ int n = sc.nextInt(); long a[] = new long[n]; for (int i = 0; i<n; i++) { a[i] = sc.nextLong(); } sort(a); long ans = fun1(a,n,0,0); System.out.println(ans); } } } //code By Priyanshu
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
adb26a26c6fab9a64074ba2fc390aa95
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class A { static int mod = 1000000007; public static void main(String[] args) { FastScanner sc = new FastScanner(); int yo = sc.nextInt(); while (yo-- > 0) { int n = sc.nextInt(); int[] a = sc.readInts(n); if(n <= 2) { out.println(0); } else { sort(a); long ans = 0; long[] prefix = new long[n]; for(int i = 0; i < n; i++) { if(i == 0) prefix[i] = a[i]; else prefix[i] = prefix[i-1] + a[i]; } for(int i = 0; i < n-2; i++) { ans -= a[i+2]*1l*(i+1); ans += prefix[i]; } out.println(ans); } } } public static class Pair { int x; int y; public Pair(int x, int y) { this.x = x; this.y = y; } } public static void sort(int[] arr) { ArrayList<Integer> ls = new ArrayList<Integer>(); for (int x : arr) ls.add(x); Collections.sort(ls); for (int i = 0; i < arr.length; i++) arr[i] = ls.get(i); } public static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static boolean[] sieve(int N) { boolean[] sieve = new boolean[N + 1]; for (int i = 2; i <= N; i++) sieve[i] = true; for (int i = 2; i <= N; i++) { if (sieve[i]) { for (int j = 2 * i; j <= N; j += i) { sieve[j] = false; } } } return sieve; } public static long power(long x, long y, long p) { long res = 1L; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y >>= 1; x = (x * x) % p; } return res; } public static void print(int[] arr) { //for debugging only for (int x : arr) out.print(x + " "); out.println(); } static class FastScanner { private int BS = 1 << 16; private char NC = (char) 0; private byte[] buf = new byte[BS]; private int bId = 0, size = 0; private char c = NC; private double cnt = 1; private BufferedInputStream in; public FastScanner() { in = new BufferedInputStream(System.in, BS); } public FastScanner(String s) { try { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } catch (Exception e) { in = new BufferedInputStream(System.in, BS); } } private char getChar() { while (bId == size) { try { size = in.read(buf); } catch (Exception e) { return NC; } if (size == -1) return NC; bId = 0; } return (char) buf[bId++]; } public int nextInt() { return (int) nextLong(); } public int[] readInts(int N) { int[] res = new int[N]; for (int i = 0; i < N; i++) { res[i] = (int) nextLong(); } return res; } public long[] readLongs(int N) { long[] res = new long[N]; for (int i = 0; i < N; i++) { res[i] = nextLong(); } return res; } public long nextLong() { cnt = 1; boolean neg = false; if (c == NC) c = getChar(); for (; (c < '0' || c > '9'); c = getChar()) { if (c == '-') neg = true; } long res = 0; for (; c >= '0' && c <= '9'; c = getChar()) { res = (res << 3) + (res << 1) + c - '0'; cnt *= 10; } return neg ? -res : res; } public double nextDouble() { double cur = nextLong(); return c != '.' ? cur : cur + nextLong() / cnt; } public double[] readDoubles(int N) { double[] res = new double[N]; for (int i = 0; i < N; i++) { res[i] = nextDouble(); } return res; } public String next() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c > 32) { res.append(c); c = getChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while (c <= 32) c = getChar(); while (c != '\n') { res.append(c); c = getChar(); } return res.toString(); } public boolean hasNext() { if (c > 32) return true; while (true) { c = getChar(); if (c == NC) return false; else if (c > 32) return true; } } } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
04bf5b44af3f1fb0b6784512433fff8a
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class tank { static final FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) { int t = fs.nextInt(); while(t-- > 0) { run_case(); } out.close(); } static void run_case() { int n = fs.nextInt(); int[] arr = fs.readArray(n); ruffleSort(arr); for (int i = n - 1; i > 0; i--) { arr[i] -= arr[i - 1]; //out.print(arr[i] + " "); } //out.println(); long ans = 0; for (int i = 1; i < n; i++) { ans -= (i) * (long) arr[i] * (long) (n - i - 1); ans -= (i - 1) * (long) arr[i]; } out.println(ans); } static void ruffleSort(int[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } String nextLine(){ try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return ""; } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
ee1d7d794e423d945294dc54ae031d2d
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; public class _1541_C { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int t = Integer.parseInt(in.readLine()); while(t-- > 0) { int n = Integer.parseInt(in.readLine()); int[] d = new int[n]; StringTokenizer line = new StringTokenizer(in.readLine()); for(int i = 0; i < n; i++) { d[i] = Integer.parseInt(line.nextToken()); } Arrays.sort(d); int[] dif = new int[n - 1]; for(int i = 1; i < n; i++) { dif[i - 1] = d[i] - d[i - 1]; } long res = 0; for(int i = 0; i < n - 1; i++) { long contained = chooseTwo(n) - chooseTwo(i + 1) - chooseTwo(n - (i + 1)); res += dif[i]; res -= contained * dif[i]; } out.println(res); } in.close(); out.close(); } static long chooseTwo(int x) { return (long)x * (x - 1) / 2; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
3f628d1d8a3c5b69897fb989597902da
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package greatgraphs; import java.util.*; import java.io.*; public class greatgraphs { public static void main(String[] args) throws IOException { BufferedReader fin = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(fin.readLine()); StringBuilder fout = new StringBuilder(); while(t-- > 0) { int n = Integer.parseInt(fin.readLine()); StringTokenizer st = new StringTokenizer(fin.readLine()); Integer[] nums = new Integer[n]; for(int i = 0; i < n; i++) { nums[i] = Integer.parseInt(st.nextToken()); } Arrays.sort(nums); long ans = 0; long diffSum = 0; for(int i = 1; i < n; i++) { long prev = nums[i - 1]; long cur = nums[i]; diffSum += (cur - prev) * i; ans += (cur - prev) - diffSum; } fout.append(ans).append("\n"); } System.out.print(fout); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
542def1fb2c9bc6e456a3bb856c69cda
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import static java.util.Arrays.*; import java.util.*; public class C { public Object solve () { int N = sc.nextInt(); long [] A = sc.nextLongs(); sort(A); long res = 0, S = 0; for (int i : rep(1, N)) { res += A[i] - A[i-1]; res -= i * A[i] - S; S += A[i]; } return res; } private static final int CONTEST_TYPE = 2; private static void init () { } private static Long [] boxed (long ... A) { return stream(A).mapToObj(x -> x).toArray(Long[]::new); } private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; } private static long [] sort (long [] A) { Long [] AA = boxed(A); Collections.shuffle(asList(AA)); Arrays.sort(unboxed(AA, A)); return A; } private static long [] unboxed (Long [] A) { return stream(A).mapToLong(x -> x).toArray(); } private static long [] unboxed (Long [] A, long [] a) { System.arraycopy(unboxed(A), 0, a, 0, A.length); return a; } //////////////////////////////////////////////////////////////////////////////////// OFF private static IOUtils.MyScanner sc = new IOUtils.MyScanner(); private static class IOUtils { public static class MyScanner { public String next () { newLine(); return line[index++]; } public int nextInt () { return Integer.parseInt(next()); } public String nextLine () { line = null; return readLine(); } public String [] nextStrings () { return split(nextLine()); } public long [] nextLongs () { String [] S = nextStrings(); int N = S.length; long [] res = new long [N]; for (int i = 0; i < N; ++i) res[i] = Long.parseLong(S[i]); return res; } ////////////////////////////////////////////// private boolean eol () { return index == line.length; } private String readLine () { try { int b; StringBuilder res = new StringBuilder(); while ((b = System.in.read()) < ' ') continue; res.append((char)b); while ((b = System.in.read()) >= ' ') res.append((char)b); return res.toString(); } catch (Exception e) { throw new Error (e); } } private MyScanner () { try { while (System.in.available() == 0) Thread.sleep(1); start(); } catch (Exception e) { throw new Error(e); } } private String [] line; private int index; private void newLine () { if (line == null || eol()) { line = split(readLine()); index = 0; } } private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; } } private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); } private static String buildDelim (String delim, Object o, Object ... A) { java.util.List<String> str = new java.util.ArrayList<>(); append(str, o); for (Object p : A) append(str, p); return String.join(delim, str.toArray(new String [0])); } ////////////////////////////////////////////////////////////////////////////////// private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########"); private static void start () { if (t == 0) t = millis(); } private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, Object o) { if (o.getClass().isArray()) { int len = java.lang.reflect.Array.getLength(o); for (int i = 0; i < len; ++i) f.accept(java.lang.reflect.Array.get(o, i)); } else if (o instanceof Iterable<?>) ((Iterable<?>)o).forEach(f::accept); else g.accept(o instanceof Double ? formatter.format(o) : o); } private static void append (java.util.List<String> str, Object o) { append(x -> append(str, x), x -> str.add(x.toString()), o); } private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out); private static void flush () { pw.flush(); System.out.flush(); } private static void print (Object o, Object ... A) { String res = build(o, A); if (DEBUG == 2) err(res, '(', time(), ')'); if (res.length() > 0) pw.println(res); if (DEBUG == 1) flush(); } private static void err (Object o, Object ... A) { System.err.println(build(o, A)); } private static int DEBUG; private static void exit () { String end = "------------------" + System.lineSeparator() + time(); switch(DEBUG) { case 1: print(end); break; case 2: err(end); break; } IOUtils.pw.close(); System.out.flush(); System.exit(0); } private static long t; private static long millis () { return System.currentTimeMillis(); } private static String time () { return "Time: " + (millis() - t) / 1000.0; } private static void run (int N) { try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); } catch (Throwable t) {} for (int n = 1; n <= N; ++n) { Object res = new C().solve(); if (res != null) { @SuppressWarnings("all") Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res; print(o); } } exit(); } } //////////////////////////////////////////////////////////////////////////////////// public static void main (String[] args) { @SuppressWarnings("all") int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt(); init(); IOUtils.run(N); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 11
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
be50de19965f163c9665a11eb9be9139
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0){ int n = sc.nextInt(); // n = n-1; Integer[] d = new Integer[n]; int i; // sc.nextInt(); for(i=0; i<n; i++){ d[i] = sc.nextInt(); } if(n==1){ System.out.println(0); t--; continue; } if(n==2){ System.out.println(d[0]<0?d[0]:0); t--; continue; } Arrays.sort(d); long ans = 0; // for(i=0; i<n; i++){ // if(d[i] != d[n-1]) // ans-=d[i]; // } // System.out.println(ans); long tmp = 0; int[] diff = new int[n-1]; long[] ds = new long[n]; ds[0]=0; for(i=0;i<n-1;i++){ diff[i] = d[i+1]-d[i]; tmp+=diff[i]; ds[i+1] = tmp; // System.out.println(diff[i]+ " " + ds[i+1]); } tmp = 0; for(i=1;i<n;i++){ tmp+=ds[i]; } for(i=1;i<n;i++){ // System.out.println(tmp); ans-=tmp; // System.out.println(ans); tmp=tmp-(long)(n-i)*(diff[i-1]); } ans+=ds[n-1]; System.out.println(ans); t--; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
ab0b4dcdb5698011f06a8152ae9006e6
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; import java.lang.Math; public class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0){ int n = sc.nextInt(); // n = n-1; Integer[] d = new Integer[n]; int i; // sc.nextInt(); for(i=0; i<n; i++){ d[i] = sc.nextInt(); } if(n==1){ System.out.println(0); t--; continue; } if(n==2){ System.out.println(d[0]<0?d[0]:0); t--; continue; } Arrays.sort(d); long ans = 0; // for(i=0; i<n; i++){ // if(d[i] != d[n-1]) // ans-=d[i]; // } // System.out.println(ans); long tmp = 0; int[] diff = new int[n-1]; long[] ds = new long[n]; ds[0]=0; for(i=0;i<n-1;i++){ diff[i] = d[i+1]-d[i]; tmp+=diff[i]; ds[i+1] = tmp; // System.out.println(diff[i]+ " " + ds[i+1]); } tmp = 0; for(i=1;i<n;i++){ tmp+=ds[i]; } for(i=0;i<n-1;i++){ // System.out.println(tmp); ans-=(long)diff[i]*(i+1)*(n-1-i); // System.out.println(ans); // tmp=tmp-(n-i)*(diff[i-1]); } ans+=ds[n-1]; System.out.println(ans); t--; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
a53b0f231972e2a3aa3b6b33ef2ac4de
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; public class DSA { public static void main(String[]args) { Scanner sc = new Scanner (System.in); int t = sc.nextInt(); for(int p= 0;p<t;p++) { long size= sc.nextInt(); long inp[] = new long[(int) size]; for(int i=0;i<size;i++) { inp[i]=sc.nextInt(); } Arrays.sort(inp); long[]temp = new long[(int)size-1]; for(int i =0;i<size-1;i++) { temp[i]=inp[i+1]-inp[i]; } long total=0; for(int i=0;i<size-1;i++) { total+= temp[i]*((size-1-i)*i+(size-2-i)); } System.out.println(-1*total); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
a211c7fcfd87621c3c547bce6b2770bd
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; public class C { static class InputReader { /** * The default size of the InputReader's buffer is 2^16 -> 65,536 characters */ private static final int DEFAULT_BUFFER_SIZE = 1 << 16; // Change this to increase your input size // /** * The default stream for the InputReader is standard input. */ private static final InputStream DEFAULT_STREAM = System.in; /** * The maximum number of accurate decimal digits the method {@link #nextDoubleFast() nextDoubleFast()} can read. * Currently this value is set to 21 because it is the maximum number of digits a double precision float can have at the moment. */ private static final int MAX_DECIMAL_PRECISION = 21; // 'c' is used to refer to the current character in the stream private int c; // Variables associated with the byte buffer. private byte[] buf; private int bufferSize, bufIndex, numBytesRead; private InputStream stream; // End Of File (EOF) character private static final byte EOF = -1; // New line character: '\n' private static final byte NEW_LINE = 10; // Carriage return character: '\r' private static final byte CARRIAGE_RETURN = 13; // Space character: ' ' private static final byte SPACE = 32; // Dash character: '-' private static final byte DASH = 45; // Dot character: '.' private static final byte DOT = 46; // A reusable character buffer when reading string data. private char[] charBuffer; // Primitive data type lookup tables used for optimizations private static byte[] bytes = new byte[58]; private static int[] ints = new int[58]; private static char[] chars = new char[128]; static { char ch = ' '; int value = 0; byte _byte = 0; for (int i = 48; i < 58; i++) bytes[i] = _byte++; for (int i = 48; i < 58; i++) ints[i] = value++; for (int i = 32; i < 128; i++) chars[i] = ch++; } // Primitive double lookup table used for optimizations. private static final double[][] doubles = { {0.0d, 0.00d, 0.000d, 0.0000d, 0.00000d, 0.000000d, 0.0000000d, 0.00000000d, 0.000000000d, 0.0000000000d, 0.00000000000d, 0.000000000000d, 0.0000000000000d, 0.00000000000000d, 0.000000000000000d, 0.0000000000000000d, 0.00000000000000000d, 0.000000000000000000d, 0.0000000000000000000d, 0.00000000000000000000d, 0.000000000000000000000d}, {0.1d, 0.01d, 0.001d, 0.0001d, 0.00001d, 0.000001d, 0.0000001d, 0.00000001d, 0.000000001d, 0.0000000001d, 0.00000000001d, 0.000000000001d, 0.0000000000001d, 0.00000000000001d, 0.000000000000001d, 0.0000000000000001d, 0.00000000000000001d, 0.000000000000000001d, 0.0000000000000000001d, 0.00000000000000000001d, 0.000000000000000000001d}, {0.2d, 0.02d, 0.002d, 0.0002d, 0.00002d, 0.000002d, 0.0000002d, 0.00000002d, 0.000000002d, 0.0000000002d, 0.00000000002d, 0.000000000002d, 0.0000000000002d, 0.00000000000002d, 0.000000000000002d, 0.0000000000000002d, 0.00000000000000002d, 0.000000000000000002d, 0.0000000000000000002d, 0.00000000000000000002d, 0.000000000000000000002d}, {0.3d, 0.03d, 0.003d, 0.0003d, 0.00003d, 0.000003d, 0.0000003d, 0.00000003d, 0.000000003d, 0.0000000003d, 0.00000000003d, 0.000000000003d, 0.0000000000003d, 0.00000000000003d, 0.000000000000003d, 0.0000000000000003d, 0.00000000000000003d, 0.000000000000000003d, 0.0000000000000000003d, 0.00000000000000000003d, 0.000000000000000000003d}, {0.4d, 0.04d, 0.004d, 0.0004d, 0.00004d, 0.000004d, 0.0000004d, 0.00000004d, 0.000000004d, 0.0000000004d, 0.00000000004d, 0.000000000004d, 0.0000000000004d, 0.00000000000004d, 0.000000000000004d, 0.0000000000000004d, 0.00000000000000004d, 0.000000000000000004d, 0.0000000000000000004d, 0.00000000000000000004d, 0.000000000000000000004d}, {0.5d, 0.05d, 0.005d, 0.0005d, 0.00005d, 0.000005d, 0.0000005d, 0.00000005d, 0.000000005d, 0.0000000005d, 0.00000000005d, 0.000000000005d, 0.0000000000005d, 0.00000000000005d, 0.000000000000005d, 0.0000000000000005d, 0.00000000000000005d, 0.000000000000000005d, 0.0000000000000000005d, 0.00000000000000000005d, 0.000000000000000000005d}, {0.6d, 0.06d, 0.006d, 0.0006d, 0.00006d, 0.000006d, 0.0000006d, 0.00000006d, 0.000000006d, 0.0000000006d, 0.00000000006d, 0.000000000006d, 0.0000000000006d, 0.00000000000006d, 0.000000000000006d, 0.0000000000000006d, 0.00000000000000006d, 0.000000000000000006d, 0.0000000000000000006d, 0.00000000000000000006d, 0.000000000000000000006d}, {0.7d, 0.07d, 0.007d, 0.0007d, 0.00007d, 0.000007d, 0.0000007d, 0.00000007d, 0.000000007d, 0.0000000007d, 0.00000000007d, 0.000000000007d, 0.0000000000007d, 0.00000000000007d, 0.000000000000007d, 0.0000000000000007d, 0.00000000000000007d, 0.000000000000000007d, 0.0000000000000000007d, 0.00000000000000000007d, 0.000000000000000000007d}, {0.8d, 0.08d, 0.008d, 0.0008d, 0.00008d, 0.000008d, 0.0000008d, 0.00000008d, 0.000000008d, 0.0000000008d, 0.00000000008d, 0.000000000008d, 0.0000000000008d, 0.00000000000008d, 0.000000000000008d, 0.0000000000000008d, 0.00000000000000008d, 0.000000000000000008d, 0.0000000000000000008d, 0.00000000000000000008d, 0.000000000000000000008d}, {0.9d, 0.09d, 0.009d, 0.0009d, 0.00009d, 0.000009d, 0.0000009d, 0.00000009d, 0.000000009d, 0.0000000009d, 0.00000000009d, 0.000000000009d, 0.0000000000009d, 0.00000000000009d, 0.000000000000009d, 0.0000000000000009d, 0.00000000000000009d, 0.000000000000000009d, 0.0000000000000000009d, 0.00000000000000000009d, 0.000000000000000000009d} }; /** * Create an InputReader that reads from standard input. */ public InputReader() { this(DEFAULT_STREAM, DEFAULT_BUFFER_SIZE); } /** * Create an InputReader that reads from standard input. * * @param bufferSize The buffer size for this input reader. */ public InputReader(int bufferSize) { this(DEFAULT_STREAM, bufferSize); } /** * Create an InputReader that reads from standard input. * * @param stream Takes an InputStream as a parameter to read from. */ public InputReader(InputStream stream) { this(stream, DEFAULT_BUFFER_SIZE); } /** * Create an InputReader that reads from standard input. * * @param stream Takes an {@link InputStream#InputStream() InputStream} as a parameter to read from. * @param bufferSize The size of the buffer to use. */ public InputReader(InputStream stream, int bufferSize) { if (stream == null || bufferSize <= 0) throw new IllegalArgumentException(); buf = new byte[bufferSize]; charBuffer = new char[128]; this.bufferSize = bufferSize; this.stream = stream; } /** * Reads a single character from the input stream. * * @return Returns the byte value of the next character in the buffer and EOF * at the end of the stream. * @throws IOException throws exception if there is no more data to read */ private byte read() throws IOException { if (numBytesRead == EOF) throw new IOException(); if (bufIndex >= numBytesRead) { bufIndex = 0; numBytesRead = stream.read(buf); if (numBytesRead == EOF) return EOF; } return buf[bufIndex++]; } /** * Read values from the input stream until you reach a character with a * higher ASCII value than 'token'. * * @param token The token is a value which we use to stop reading junk out of * the stream. * @return Returns 0 if a value greater than the token was reached or -1 if * the end of the stream was reached. * @throws IOException Throws exception at end of stream. */ private int readJunk(int token) throws IOException { if (numBytesRead == EOF) return EOF; // Seek to the first valid position index do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > token) return 0; bufIndex++; } // reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return EOF; bufIndex = 0; } while (true); } /** * Reads a single byte from the input stream. * * @return The next byte in the input stream * @throws IOException Throws exception at end of stream. */ public byte nextByte() throws IOException { return (byte) nextInt(); } /** * Reads a 32 bit signed integer from input stream. * * @return The next integer value in the stream. * @throws IOException Throws exception at end of stream. */ public int nextInt() throws IOException { if (readJunk(DASH - 1) == EOF) throw new IOException(); int sgn = 1, res = 0; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return res * sgn; bufIndex = 0; } while (true); } /** * Reads a 64 bit signed long from input stream. * * @return The next long value in the stream. * @throws IOException Throws exception at end of stream. */ public long nextLong() throws IOException { if (readJunk(DASH - 1) == EOF) throw new IOException(); int sgn = 1; long res = 0L; c = buf[bufIndex]; if (c == DASH) { sgn = -1; bufIndex++; } do { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { res = (res << 3) + (res << 1); res += ints[buf[bufIndex++]]; } else { bufIndex++; return res * sgn; } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return res * sgn; bufIndex = 0; } while (true); } /** * Doubles the size of the internal char buffer for strings */ private void doubleCharBufferSize() { char[] newBuffer = new char[charBuffer.length << 1]; for (int i = 0; i < charBuffer.length; i++) newBuffer[i] = charBuffer[i]; charBuffer = newBuffer; } /** * Reads a line from the input stream. * * @return Returns a line from the input stream in the form a String not * including the new line character. Returns <code>null</code> when there are * no more lines. * @throws IOException Throws IOException when something terrible happens. */ public String nextLine() throws IOException { try { c = read(); } catch (IOException e) { return null; } if (c == NEW_LINE) return ""; // Empty line if (c == EOF) return null; // EOF int i = 0; charBuffer[i++] = (char) c; do { while (bufIndex < numBytesRead) { if (buf[bufIndex] != NEW_LINE && buf[bufIndex] != CARRIAGE_RETURN) { if (i == charBuffer.length) doubleCharBufferSize(); charBuffer[i++] = (char) buf[bufIndex++]; } else { if(buf[bufIndex] == CARRIAGE_RETURN) bufIndex++; bufIndex++; return new String(charBuffer, 0, i); } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return new String(charBuffer, 0, i); bufIndex = 0; } while (true); } // Reads a string of characters from the input stream. // The delimiter separating a string of characters is set to be: // any ASCII value <= 32 meaning any spaces, new lines, EOF, tabs... public String nextString() throws IOException { if (numBytesRead == EOF) return null; if (readJunk(SPACE) == EOF) return null; for (int i = 0; ; ) { while (bufIndex < numBytesRead) { if (buf[bufIndex] > SPACE) { if (i == charBuffer.length) doubleCharBufferSize(); charBuffer[i++] = (char) buf[bufIndex++]; } else { bufIndex++; return new String(charBuffer, 0, i); } } // Reload buffer numBytesRead = stream.read(buf); if (numBytesRead == EOF) return new String(charBuffer, 0, i); bufIndex = 0; } } // Returns an exact value a double value from the input stream. public double nextDouble() throws IOException { String doubleVal = nextString(); if (doubleVal == null) throw new IOException(); return Double.valueOf(doubleVal); } // Very quickly reads a double value from the input stream (~3x faster than nextDouble()). However, // this method may provide a slightly less accurate reading than .nextDouble() if there are a lot // of digits (~16+). In particular, it will only read double values with at most 21 digits after // the decimal point and the reading my be as inaccurate as ~5*10^-16 from the true value. public double nextDoubleFast() throws IOException { c = read(); int sgn = 1; while (c <= SPACE) c = read(); // while c is either: ' ', '\n', EOF if (c == DASH) { sgn = -1; c = read(); } double res = 0.0; // while c is not: ' ', '\n', '.' or -1 while (c > DOT) { res *= 10.0; res += ints[c]; c = read(); } if (c == DOT) { int i = 0; c = read(); // while c is digit and we are less than the maximum decimal precision while (c > SPACE && i < MAX_DECIMAL_PRECISION) { res += doubles[ints[c]][i++]; c = read(); } } return res * sgn; } // Read an array of n byte values public byte[] nextByteArray(int n) throws IOException { byte[] ar = new byte[n]; for (int i = 0; i < n; i++) ar[i] = nextByte(); return ar; } // Read an integer array of size n public int[] nextIntArray(int n) throws IOException { int[] ar = new int[n]; for (int i = 0; i < n; i++) ar[i] = nextInt(); return ar; } // Read a long array of size n public long[] nextLongArray(int n) throws IOException { long[] ar = new long[n]; for (int i = 0; i < n; i++) ar[i] = nextLong(); return ar; } // read an of doubles of size n public double[] nextDoubleArray(int n) throws IOException { double[] ar = new double[n]; for (int i = 0; i < n; i++) ar[i] = nextDouble(); return ar; } // Quickly read an array of doubles public double[] nextDoubleArrayFast(int n) throws IOException { double[] ar = new double[n]; for (int i = 0; i < n; i++) ar[i] = nextDoubleFast(); return ar; } // Read a string array of size n public String[] nextStringArray(int n) throws IOException { String[] ar = new String[n]; for (int i = 0; i < n; i++) { String str = nextString(); if (str == null) throw new IOException(); ar[i] = str; } return ar; } // Read a 1-based byte array of size n+1 public byte[] nextByteArray1(int n) throws IOException { byte[] ar = new byte[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextByte(); return ar; } // Read a 1-based integer array of size n+1 public int[] nextIntArray1(int n) throws IOException { int[] ar = new int[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextInt(); return ar; } // Read a 1-based long array of size n+1 public long[] nextLongArray1(int n) throws IOException { long[] ar = new long[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextLong(); return ar; } // Read a 1-based double array of size n+1 public double[] nextDoubleArray1(int n) throws IOException { double[] ar = new double[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextDouble(); return ar; } // Quickly read a 1-based double array of size n+1 public double[] nextDoubleArrayFast1(int n) throws IOException { double[] ar = new double[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextDoubleFast(); return ar; } // Read a 1-based string array of size n+1 public String[] nextStringArray1(int n) throws IOException { String[] ar = new String[n + 1]; for (int i = 1; i <= n; i++) ar[i] = nextString(); return ar; } // Read a two dimensional matrix of bytes of size rows x cols public byte[][] nextByteMatrix(int rows, int cols) throws IOException { byte[][] matrix = new byte[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextByte(); return matrix; } // Read a two dimensional matrix of ints of size rows x cols public int[][] nextIntMatrix(int rows, int cols) throws IOException { int[][] matrix = new int[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextInt(); return matrix; } // Read a two dimensional matrix of longs of size rows x cols public long[][] nextLongMatrix(int rows, int cols) throws IOException { long[][] matrix = new long[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextLong(); return matrix; } // Read a two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrix(int rows, int cols) throws IOException { double[][] matrix = new double[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextDouble(); return matrix; } // Quickly read a two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrixFast(int rows, int cols) throws IOException { double[][] matrix = new double[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextDoubleFast(); return matrix; } // Read a two dimensional matrix of Strings of size rows x cols public String[][] nextStringMatrix(int rows, int cols) throws IOException { String[][] matrix = new String[rows][cols]; for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) matrix[i][j] = nextString(); return matrix; } // Read a 1-based two dimensional matrix of bytes of size rows x cols public byte[][] nextByteMatrix1(int rows, int cols) throws IOException { byte[][] matrix = new byte[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextByte(); return matrix; } // Read a 1-based two dimensional matrix of ints of size rows x cols public int[][] nextIntMatrix1(int rows, int cols) throws IOException { int[][] matrix = new int[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextInt(); return matrix; } // Read a 1-based two dimensional matrix of longs of size rows x cols public long[][] nextLongMatrix1(int rows, int cols) throws IOException { long[][] matrix = new long[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextLong(); return matrix; } // Read a 1-based two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrix1(int rows, int cols) throws IOException { double[][] matrix = new double[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextDouble(); return matrix; } // Quickly read a 1-based two dimensional matrix of doubles of size rows x cols public double[][] nextDoubleMatrixFast1(int rows, int cols) throws IOException { double[][] matrix = new double[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextDoubleFast(); return matrix; } // Read a 1-based two dimensional matrix of Strings of size rows x cols public String[][] nextStringMatrix1(int rows, int cols) throws IOException { String[][] matrix = new String[rows + 1][cols + 1]; for (int i = 1; i <= rows; i++) for (int j = 1; j <= cols; j++) matrix[i][j] = nextString(); return matrix; } // Closes the input stream public void close() throws IOException { stream.close(); } } // region variables static InputReader sc = new InputReader(); static OutputStream outputStream = System.out; static PrintWriter w = new PrintWriter(outputStream); static long timeStart; // endregion private static void initiateIO() throws IOException { if (System.getProperty("ONLINE_JUDGE") == null) { try { w = new PrintWriter("output.txt"); sc = new InputReader(new FileInputStream("input.txt")); } catch (Exception e) { throw new IOException(); } } } public static void main(String[] args) throws IOException { initiateIO(); int t = sc.nextInt(); while(t-- > 0) { solve(); } w.close(); } static void solve() throws IOException { int n = sc.nextInt(); ArrayList<Long> arr = new ArrayList<>(); long ans = 0; for(int i = 0; i < n; i++) { long curr = sc.nextLong(); arr.add(curr); } Collections.sort(arr); long prev = 0; for(int i = 1; i < n; i++) { long currDiff = (arr.get(i-1)-arr.get(i)); long positions = i-1; long prevAns = ans; ans += (prev + (positions*currDiff)); ans += currDiff; prev = ans-prevAns; } for(int i = 1; i < n; i++) { ans += arr.get(i)-arr.get(i-1); } w.println(ans); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
ae1a106cebea4ec0e55a200a4f81eaaa
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; public class tr0 { static PrintWriter out; static StringBuilder sb; static long mod = 998244353; static long inf = (long) 1e16; static int n, m, k; static ArrayList<Integer>[] ad; static int[][] remove, add; static long[][] memo; static boolean vis[]; static long[] inv, ncr[]; static HashMap<Integer, Integer> hm; static int[] pre, suf, Smax[], Smin[]; static int idmax, idmin; static ArrayList<Integer> av; static HashMap<Integer, Integer> mm; static boolean[] msks; static int[] lazy[], lazyCount; static int[] dist; static int[][] P; static int st, ed, N; static ArrayList<Integer> gl; static int[] a, c; public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); out = new PrintWriter(System.out); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); int[] a = sc.nextArrIntSorted(n); if (n <= 2) out.println(0); else { long sum = 0; long [] diff=new long [n]; for(int i=1;i<n;i++) diff[i]=a[i]-a[i-1]; long [] diff1=diff.clone(); for (int i = n-2; i >0; i--) { diff[i]+=diff[i+1]; sum+=diff[i]; } long su=sum-diff1[n-1]*(n-2); long h=n-3; // System.out.println(su+" "+Arrays.toString(diff)); for(int i=n-2;i>1;i--) { su-=diff1[i]*h; sum+=su; // System.out.println(h+" "+su+" "+diff[i]); h--; } out.println(-sum); } } out.flush(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String file) throws Exception { br = new BufferedReader(new FileReader(file)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public int[] nextArrInt(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextArrLong(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public int[] nextArrIntSorted(int n) throws IOException { int[] a = new int[n]; Integer[] a1 = new Integer[n]; for (int i = 0; i < n; i++) a1[i] = nextInt(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].intValue(); return a; } public long[] nextArrLongSorted(int n) throws IOException { long[] a = new long[n]; Long[] a1 = new Long[n]; for (int i = 0; i < n; i++) a1[i] = nextLong(); Arrays.sort(a1); for (int i = 0; i < n; i++) a[i] = a1[i].longValue(); return a; } public boolean ready() throws IOException { return br.ready(); } public void waitForInput() throws InterruptedException { Thread.sleep(3000); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
64d655e19c812a05e016c996bb1b2a8d
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class PurpleCrayonC { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); long[] arr = readArr(N, infile, st); if(N == 1) { sb.append("0\n"); continue; } Arrays.sort(arr); long res=0L; for(int i=1;i<N;i++){ res-=(arr[i]-arr[i-1])*i*(N-i); } /*long[] diffs = new long[N-1]; for(int i=0; i < N-1; i++) diffs[i] = arr[i+1]-arr[i]; long res = 0L; for(int i=0; i < N-1; i++) res -= diffs[i]*(i+1)*(N-1-i); */ //System.out.println("! "+diffs[0]); //for(long x: diffs) // res += x; res+=arr[N-1]; sb.append(res+"\n"); } System.out.print(sb); } public static long[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception { long[] arr = new long[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Long.parseLong(st.nextToken()); return arr; } /*public static void sort(int[] arr) { //because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); }*/ }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
9c43134394b0d6eef971b2e9753229f4
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class PurpleCrayonC { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = readArr(N, infile, st); if(N == 1) { sb.append("0\n"); continue; } Arrays.sort(arr); long[] diffs = new long[N-1]; for(int i=0; i < N-1; i++) diffs[i] = arr[i+1]-arr[i]; long res = 0L; for(int i=0; i < N-1; i++) res -= diffs[i]*(i+1)*(N-1-i); //System.out.println("! "+diffs[0]); //for(long x: diffs) // res += x; res+=arr[N-1]; sb.append(res+"\n"); } System.out.print(sb); } 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; } /*public static void sort(int[] arr) { //because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); }*/ }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
0dbf5b53be5ddcc5a538308111ca9f18
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/* stream Butter! eggyHide eggyVengeance I need U xiao rerun when */ import static java.lang.Math.max; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.System.out; import java.util.*; import java.io.*; import java.math.*; public class PurpleCrayonC { public static void main(String hi[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = readArr(N, infile, st); if(N == 1) { sb.append("0\n"); continue; } Arrays.sort(arr); long[] diffs = new long[N-1]; for(int i=0; i < N-1; i++) diffs[i] = arr[i+1]-arr[i]; long res = 0L; for(int i=0; i < N-1; i++) res -= diffs[i]*(i+1)*(N-1-i); //System.out.println("! "+diffs[0]); for(long x: diffs) res += x; sb.append(res+"\n"); } System.out.print(sb); } 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; } /*public static void sort(int[] arr) { //because Arrays.sort() uses quicksort which is dumb //Collections.sort() uses merge sort ArrayList<Integer> ls = new ArrayList<Integer>(); for(int x: arr) ls.add(x); Collections.sort(ls); for(int i=0; i < arr.length; i++) arr[i] = ls.get(i); }*/ }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
77c055c3164244d10816c81c34b83f9b
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; public class C_Great_Graphs{ public static void main(String[] args) { FastScanner s= new FastScanner(); StringBuilder res = new StringBuilder(); int t=s.nextInt(); int p=0; while(p<t){ int n=s.nextInt(); long array[]= new long[n]; for(int i=0;i<n;i++){ array[i]=s.nextLong(); } Arrays.sort(array); long sum=0; for(int i=1;i<n;i++){ sum+=(array[i]-array[i-1]); } long prev=0; for(int i=1;i<n;i++){ long num=array[i-1]-array[i]; num=num*i; num+=prev; sum+=num; prev=num; } res.append(sum+"\n"); p++; } System.out.println(res); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
b5a443480bb8c2e71c1a103f321a10e4
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package com.cf.div2.c728; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { static PrintWriter out = new PrintWriter(System.out); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); } Arrays.sort(arr); long sum = arr[n - 1]; long neg = 0; for (int i = 1; i < n; i++) { neg += (arr[i] - arr[i - 1]) * i; sum -= neg; } out.println(sum); } out.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
bb2ad54d2b97b6233a4a989dfef967c7
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package com.cf.div2.c728; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { static PrintWriter out = new PrintWriter(System.out); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); } Arrays.sort(arr); long sum = arr[n - 1]; long[] neg = new long[n]; neg[0] = 0; for (int i = 1; i < n; i++) { neg[i] = neg[i - 1] + (arr[i] - arr[i - 1]) + (arr[i] - arr[i - 1]) * (i - 1); sum -= neg[i]; } out.println(sum); } out.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
d77fe9be7fe346be96537ed87eec575b
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException, FileNotFoundException { // Scanner in = new Scanner(new File("test.in")); Scanner in = new Scanner(System.in); int T = in.nextInt(); for(int t = 0; t < T; t++){ int N = in.nextInt(); long[] d = new long[N]; for(int i = 0; i < N; i++){ d[i] = in.nextLong(); } Arrays.sort(d); long ans = d[d.length - 1]; long sum = 0; for(int i = 1; i < N; i++){ ans += sum; ans -= (d[i])*i; sum += d[i]; } System.out.println(ans); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
4bd9f113545e8ece948674f61a5942e8
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { inputAndSettingData(); } static long solve(long[] arr, int N) { long ans = 0; long sum = 0; Arrays.sort(arr); for (int i = 1; i < N; i++) { ans += arr[i] - arr[i - 1] + sum - i * arr[i]; sum += arr[i]; } return ans; } static void inputAndSettingData() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); StringBuilder out = new StringBuilder(); int T = Integer.parseInt(st.nextToken()); while (T-- > 0) { int N = Integer.parseInt(br.readLine()); long[] arr = new long[N]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < N; i++) { arr[i] = Long.parseLong(st.nextToken()); } out.append(solve(arr, N)).append("\n"); } System.out.println(out); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
6169f7f0fe595b4b30f392a8ebc7a7f1
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { inputAndSettingData(); } static long solve(long[] arr, int N) { long ans = 0; Arrays.sort(arr); long sum = 0; for (int i = 1; i < N; i++) { ans += arr[i] - arr[i - 1]; ans += sum - i * arr[i]; sum += arr[i]; } return ans; } static void inputAndSettingData() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); StringBuilder out = new StringBuilder(); int T = Integer.parseInt(st.nextToken()); while (T-- > 0) { int N = Integer.parseInt(br.readLine()); long[] arr = new long[N]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < N; i++) { arr[i] = Long.parseLong(st.nextToken()); } out.append(solve(arr, N)).append("\n"); } System.out.println(out); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
faec5158ad78902d298c7518466dfbd3
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class CFMain3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); List<int[]> arrays = new ArrayList<>(); for (int i = 0; i < t; i++) { int n = sc.nextInt(); int[] array = new int[n]; for (int j = 0; j < n; j++) { array[j] = sc.nextInt(); } arrays.add(array); } sc.close(); for (int[] array : arrays) { Arrays.sort(array); long totalWeight = 0; long nonNegatives = 0; long stepNegativeWeight = 0; for (int i = 0; i < array.length; i++) { int a = array[i]; if (a < 0) { totalWeight += a; } else if (a >= 0) { nonNegatives++; if (nonNegatives == 1) { continue; } long delta = a - array[i - 1]; stepNegativeWeight += delta * (nonNegatives - 1); totalWeight += delta; totalWeight -= stepNegativeWeight; } } System.out.println(totalWeight); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
b93019c5951e4220df8d235a9ee24bf3
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class C { private static void solve(FastScanner sc){ int n = sc.nextInt(); long[]arr = new long[n]; for(int i = 0;i < n;i++) arr[i] = sc.nextLong(); Arrays.sort(arr); long sum = 0; long ans = 0; for(int i = 0;i < n;i++){ ans -= arr[i] * i - sum; sum += arr[i]; } ans += arr[n - 1]; System.out.println(ans); } public static void main(String[] args) { FastScanner sc = new FastScanner(); int n = sc.nextInt(); for (int i = 0; i < n; i++) { solve(sc); } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
bcdeed86819b525d68f220718ecd72a2
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; import java .lang.*; public class test { public static void main(String[] args) throws IOException{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(br.readLine()); while(t-->0) { long n=Long.parseLong(br.readLine()); String s[]=br.readLine().split("\\ "); long a[]=new long[(int)n]; Map<Integer,Integer> l=new TreeMap<>(); ArrayList<Integer> l2=new ArrayList<Integer>(); //ArrayList<Integer> l2=new ArrayList<>(); for(int i=0;i<n;i++) { a[i]=Long.parseLong(s[i]); } Arrays.sort(a); long q=0,d=0; for(int i=2;i<n;i++) { d=d+a[i-2]; q=q-(a[i]*(i-1)); q=q+d; } System.out.println(q); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
93f4176dd5d936ad7f7589ccf2bf052b
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.Scanner; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.Arrays; public class cfContest1541 { public static void main(String args[]) throws IOException { Reader scan = new Reader(); int t = scan.nextInt(); while (t-- > 0) { int n = scan.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = scan.nextInt(); } long[] pre = new long[n]; Arrays.sort(a); long res = a[n - 1]; for (int i = 1; i < n; i++) { pre[i] = pre[i - 1] + ((a[i] - a[i - 1]) * i); res -= pre[i]; } System.out.println(res); } } } class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { break; } buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) { return -ret; } return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) { c = read(); } do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) { return -ret; } return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) { buffer[0] = -1; } } private byte read() throws IOException { if (bufferPointer == bytesRead) { fillBuffer(); } return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) { return; } din.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
5d2db92fe8cc4bb4b738f388726a43af
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main(String[] args) throws java.lang.Exception { FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); int t = 1; t = in.nextInt(); while (t > 0) { --t; long n = in.nextInt(); long arr[] = new long[(int)n]; for(int i = 0;i<n;i++) arr[i] = in.nextLong(); sort(arr); long ans = 0; for(long i = n-1;i>0;i--) { arr[(int)i]-=arr[(int)i-1]; ans+=arr[(int)i]; } for(long i = 1;i<n;i++) { ans-=((i*(n-i))*arr[(int)i]); } sb.append(ans+"\n"); } System.out.print(sb); } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
00ba90d4905f2b1b1c7ac26df104e49c
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main(String[] args) throws java.lang.Exception { FastReader in = new FastReader(System.in); StringBuilder sb = new StringBuilder(); int t = 1; t = in.nextInt(); while (t > 0) { --t; long n = in.nextInt(); long arr[] = new long[(int)n]; for(int i = 0;i<n;i++) arr[i] = in.nextLong(); sort(arr); long ans = 0; for(long i = n-1;i>0;i--) { arr[(int)i]-=arr[(int)i-1]; ans+=arr[(int)i]; } for(long i = 1;i<n;i++) { ans-=((i*(n-i))*arr[(int)i]); } sb.append(ans+"\n"); } System.out.print(sb); } static long gcd(long a, long b) { if (a == 0) return b; else return gcd(b % a, a); } static long lcm(long a, long b) { return (a / gcd(a, b)) * b; } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } } class FastReader { byte[] buf = new byte[2048]; int index, total; InputStream in; FastReader(InputStream is) { in = is; } int scan() throws IOException { if (index >= total) { index = 0; total = in.read(buf); if (total <= 0) { return -1; } } return buf[index++]; } String next() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c > 32; c = scan()) { sb.append((char) c); } return sb.toString(); } String nextLine() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; StringBuilder sb = new StringBuilder(); for (; c != 10 && c != 13; c = scan()) { sb.append((char) c); } return sb.toString(); } char nextChar() throws IOException { int c; for (c = scan(); c <= 32; c = scan()) ; return (char) c; } int nextInt() throws IOException { int c, val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } long nextLong() throws IOException { int c; long val = 0; for (c = scan(); c <= 32; c = scan()) ; boolean neg = c == '-'; if (c == '-' || c == '+') { c = scan(); } for (; c >= '0' && c <= '9'; c = scan()) { val = (val << 3) + (val << 1) + (c & 15); } return neg ? -val : val; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
b4c9062208849f7d24b4a6c9eff1be66
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; import java.math.BigInteger; public class Main{ static InputReader sc; static PrintWriter pw; public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; sc = new InputReader(inputStream); pw = new PrintWriter(outputStream); solve(); pw.close(); } // static int cnt,edge; // static long ans,val; // static int time; static BigInteger min(BigInteger a, BigInteger b){ if(a.compareTo(b)<0) return a; return b; } static int[] sieveOfEratosthenes(int n, int l) { int []arr=new int [n+1]; boolean []prime = new boolean [n + 1]; Arrays.fill(prime,true); prime[0]=prime[1]=false; for (int p = 2; p <= n; p++) { if (prime[p]) { arr[p]=1; for (int i = 2*p; i <= n; i += p){ prime[i]=false; if(arr[i]==-1) continue; if((i/p)%p==0){ arr[i]=-1; continue; } arr[i]++; } } } return arr; } // static boolean poss; // static String res; public static void solve(){ int t=1; t=s(0); u:while(t-->0){ int n=s(0); long []arr=new long [n]; feedArr(arr); sort(arr); long ans=0l,sum=0l; for(int i=1;i<n;i++){ sum=(sum+((arr[i]-arr[i-1])*((long)i))); ans+=sum; } pln(arr[n-1]-ans); } } public static int calc(int f, char []chrr, int n, int cnt){ int val,ans=Integer.MAX_VALUE; for(int j=0;j<f;j++){ val=0; for(int k=j;k<n;k+=f){ if(chrr[k]=='1') val++; } ans=Math.min(ans,cnt+(n/f)-(2*val)); } return ans; } public static int getPar(int []par, int i){ if(par[i]==i) return i; return par[i]=getPar(par, par[i]); } public static void dfs(int i, boolean []vis, HashMap<Integer,Integer> lowIdx, int []upper){ vis[i]=true; int val=lowIdx.get(upper[i]); if(!vis[val]) dfs(val,vis,lowIdx,upper); } public static boolean KMPSearch(char []txt, StringBuilder ptr){ int M = ptr.length(); int N = txt.length; int lps[] = new int[M]; int j = 0; computeLPSArray(ptr, M, lps); int i = 0; while (i < N) { if (ptr.charAt(j) == txt[i]) { j++; i++; } if (j == M) { return true; } else if (i < N && ptr.charAt(j) != txt[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } return false; } public static void computeLPSArray(StringBuilder pat, int M, int lps[]){ int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat.charAt(i) == pat.charAt(len)) { len++; lps[i] = len; i++; } else { if (len != 0) { len = lps[len - 1]; } else { lps[i] = len; i++; } } } } public static void find(int i, List<Integer> list, Tree tr, char []chrr){ if(i<list.size()-1){ if(list.get(i+1)-tr.left.val==0) find(i+1,list,tr.left,chrr); else find(i+1,list,tr.right,chrr); } if(chrr[tr.val-1]=='0') tr.cnt=tr.left.cnt; if(chrr[tr.val-1]=='1') tr.cnt=tr.right.cnt; if(chrr[tr.val-1]=='?') tr.cnt=tr.left.cnt+tr.right.cnt; } public static void setCount(Tree tr, char[] chrr){ if(tr==null||tr.max==tr.min) return; setCount(tr.left, chrr); setCount(tr.right, chrr); if(chrr[tr.val-1]=='0') tr.cnt=tr.left.cnt; if(chrr[tr.val-1]=='1') tr.cnt=tr.right.cnt; if(chrr[tr.val-1]=='?') tr.cnt=tr.left.cnt+tr.right.cnt; // pln(tr.cnt); } public static Tree makeTree(int min, int max){ Tree tr=new Tree(0,min,max); if(min==max){ tr.cnt=1; return tr; } tr.left=makeTree(min, (max+min)/2); tr.right=makeTree((max+min)/2+1, max); // pln(tr.min+" "+tr.max); return tr; } public static void giveVal(Tree tr, int val){ Queue<Tree> q=new LinkedList<>(); Tree pr; q.offer(tr); while(q.size()>0&&val>0){ pr=q.poll(); pr.val=val--; if(pr.right.min!=pr.right.max){ q.offer(pr.right); } if(pr.left.min!=pr.left.max){ q.offer(pr.left); } } } public static void makePath(Tree tr, List<Integer> []list, List<Integer> temp){ if(tr.max==tr.min) return; temp.add(tr.val); list[tr.val]=new ArrayList<>(temp); makePath(tr.left, list, temp); makePath(tr.right, list, temp); temp.remove(temp.size()-1); } static class Tree{ Tree left,right; int max,min,cnt,val; Tree(int v,int mn, int mx){ val=v; max=mx; min=mn; cnt=0; } } static long fact(long p){ long ans=1l; for(long i=2;i<=p;i++) ans*=i; return ans; } static int find(int j, List<Integer> B, List<Integer> A, int i){ int l=j,r=B.size()-1,m; while(l<=r){ m=(r-l)/2+l; if(A.size()-i-1<=B.size()-m-1) l=m+1; else r=m-1; } return r; } static int findRightLimitIndex(List<Integer> B, int x){ int l=0,r=B.size()-1,m; while(l<=r){ m=(r-l)/2+l; if(B.get(m)-x<=0) l=m+1; else r=m-1; } return r; } static long nPr(long n, long r){ long ans=1; for(long i=1;i<=r;i++) ans*=(n-i+1); return ans; } static long nCr(long n, long r){ long ans=1; for(long i=1;i<=r;i++){ ans*=(n-i+1); ans/=i; } return ans; } static void update_DAG(int cur,int val, int []graph, int n) { if(val>maxx[cur]) { int x=graph[cur]; if(x!=-1) update_DAG(x,val+1,graph,n); maxx[cur]=val; update(cur,val,n); } } static int []bit, maxx; static void update(int i,int val, int n) { while(i<=n) { bit[i]=Math.max(bit[i],val); i=i+(i&(-i)); } } static int query(int i) { int ret=0; while(i>0) { ret=Math.max(ret,bit[i]); i=i-(i&(-i)); } return ret; } public static int [][]dir=new int [][]{{1,0},{0,1},{-1,0},{0,-1}}; public static int find(List<Integer> list, int x){ int l=0,r=list.size()-1,m; while(l<=r){ m=(r-l)/2+l; if(list.get(m)<=x) l=m+1; else r=m-1; } return r; } static class Node{ int val; long cost; Node next; Node(int v,long c){ val=v; next=null; cost=c; } } public static long sum(long n){ long val=0l; while(n>0){ val+=n%10; n/=10; } return val; } // static class Node{ // int left,right; // Node prev,next; // Node(int i, int v){ // left=i; // right=v; // prev=next=null; // } // void remove(){ // this.prev.next=this.next; // this.next.prev=this.prev; // } // void insert(Node node){ // node.next=this; // node.prev=this.prev; // node.prev.next=node; // this.prev=node; // } // } public static int findDiameter(int r, List<List<Integer>>list){ return findFarthest(findFarthest(r,list)[0],list)[1]; } public static int[] findFarthest(int u, List<List<Integer>>list){ int n=list.size(); boolean []vis=new boolean[n+1]; Queue<Integer>q=new LinkedList<>(); q.offer(u); vis[u]=true; int s,pr,cnt=0; int []ar=new int[]{u,0}; while(q.size()>0){ s=q.size(); while(s-->0){ pr=q.poll(); if(ar[1]<cnt){ ar[1]=cnt; ar[0]=pr; } for(int i:list.get(pr)){ if(!vis[i]){ vis[i]=true; q.offer(i); } } } cnt++; } return ar; } public static long atMostK(char []chrr, int k){ if(k<0) return 0; int l=0,cnt=0; long ans=0l; for(int i=0;i<chrr.length;i++){ if(chrr[i]=='1') cnt++; while(cnt>k){ if(chrr[l++]=='1') cnt--; } ans+=(long)(i-l)+1l; } return ans; } public static long ask(int []arr){ StringBuilder sbr=new StringBuilder(); for(int i:arr) sbr.append(i+" "); System.out.println("? "+sbr.toString()); System.out.flush(); return s(0l); } public static void sort(int []arr){ ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<arr.length;i++) list.add(arr[i]); Collections.sort(list); for(int i=0;i<arr.length;i++) arr[i]=list.get(i); } public static void sort(long []arr){ ArrayList<Long> list=new ArrayList<>(); for(int i=0;i<arr.length;i++) list.add(arr[i]); Collections.sort(list); for(int i=0;i<arr.length;i++) arr[i]=list.get(i); } public static void swap(char []chrr, int i, int j){ char temp=chrr[i]; chrr[i]=chrr[j]; chrr[j]=temp; } public static int countSetBits(long n){ int a=0; while(n>0){ a+=(n&1); n>>=1; } return a; } static class Pair{ long a; long b; Pair(long A, long B){ a=A; b=B; } //* } /*/ public int compareTo(Pair p){ return (b-p.b); } public int hashCode(){ int hashcode = (a+" "+b).hashCode(); return hashcode; } public boolean equals(Object obj){ if (obj instanceof Pair) { Pair p = (Pair) obj; return (p.a==this.a && p.b == this.b); } return false; } } //*/ static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long gcd(long a, long b) { if (b == 0) return a; return a>b?gcd(b, a % b):gcd(a, b % a); } static long fast_pow(long base,long n,long M){ if(n==0) return 1; if(n==1) return base; long halfn=fast_pow(base,n/2,M); if(n%2==0) return ( halfn * halfn ) % M; else return ( ( ( halfn * halfn ) % M ) * base ) % M; } static long modInverse(long n,long M){ return fast_pow(n,M-2,M); } public static int s(int n){ return sc.nextInt(); } public static long s(long n){ return sc.nextLong(); } public static String s(String n){ return sc.next(); } public static double s(double n){ return sc.nextDouble(); } public static void p(int n){ pw.print(n); } public static void p(long n){ pw.print(n); } public static void p(String n){ pw.print(n); } public static void p(double n){ pw.print(n); } public static void pln(int n){ pw.println(n); } public static void pln(long n){ pw.println(n); } public static void pln(String n){ pw.println(n); } public static void pln(double n){ pw.println(n); } public static void feedArr(long []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextLong(); } public static void feedArr(double []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextDouble(); } public static void feedArr(int []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.nextInt(); } public static void feedArr(String []arr){ for(int i=0;i<arr.length;i++) arr[i]=sc.next(); } public static String printArr(int []arr){ StringBuilder sbr=new StringBuilder(); for(int i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(long []arr){ StringBuilder sbr=new StringBuilder(); for(long i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(String []arr){ StringBuilder sbr=new StringBuilder(); for(String i:arr) sbr.append(i+" "); return sbr.toString(); } public static String printArr(double []arr){ StringBuilder sbr=new StringBuilder(); for(double i:arr) sbr.append(i+" "); return sbr.toString(); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } } class AncestorQuerier { int [][]dp; int N=200001; int M=22; int max; public void preCompute(int []par){ for(int i=0;i<N;i++){ if(i>=2&&i<par.length) dp[i][0]=par[i]; else dp[i][0]=-1; } for(int j=1;j<M;j++){ for(int i=0;i<N;i++){ if(dp[i][j-1]!=-1) dp[i][j]=dp[dp[i][j-1]][j-1]; } } } public int getAncestor(int val, int k) { if(k<0||val>max) return -1; if(k==0) return val; int t=(1<<(M-1)); for(int i=M-1;i>=0&&val!=-1;i--,t>>=1){ if(t<=k){ val=dp[val][i]; k-=t; } } return val; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
4496cdd610f2a9288eb89bd3692250ba
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; public class Solution{ public static void main(String[] am){ Scanner in = new Scanner(System.in); int t = in.nextInt(); while(t-->0){ int n = in.nextInt(); long ans =0; long arr[] = new long[n]; for(int i=0;i<n;i++){ arr[i] = Long.parseLong(in.next()); } Arrays.sort(arr); long sum = 0; for(int i=0;i<n;i++){ ans += sum - (arr[i]*(i)); sum += arr[i]; } ans += arr[n-1]; System.out.println(ans); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
78965d5346598c4013a123b1e6fdc1c1
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 27.06.2021 22:50:11 /*==========================================================================*/ import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { /* in.ini(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); */ long startTime = System.nanoTime(); int t = in.nextInt(), T = 1; while(t-->0) { int n = in.nextInt(); long d[] = in.readArrayL(n); ruffleSortL(d); long time = d[n-1]; long prefix[] = new long[n]; prefix[0] = d[0]; for(int i=1;i<n;i++) prefix[i] = prefix[i-1] + d[i]; for(int i=n-1;i>0;i--){ time -= (d[i]*i - prefix[i-1]); } out.println(time); //out.println("Case #"+T+": "+ans); T++; } /* startTime = System.nanoTime() - startTime; System.err.println("Time: "+(startTime/1000000)); */ out.flush(); } static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static int oo = Integer.MAX_VALUE; static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); void ini() throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch(IOException e) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } long[] readArrayL(int n) { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nextLong(); return a; } double nextDouble() { return Double.parseDouble(next()); } double[] readArrayD(int n) { double a[] = new double[n]; for(int i=0;i<n;i++) a[i] = nextDouble(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } static void ruffleSortL(long[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n); long temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
49437e885f0fd1df56b154570a116ee4
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import javax.swing.*; import java.io.*; import java.util.*; public class Main { /* Note: /usercode/Main.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } static void inorder(TreeNode root,ArrayList<Integer> ans){ if (root==null)return; inorder(root.left,ans); ans.add(root.val); inorder(root.right,ans); } static boolean find(TreeNode root,HashSet<Integer> s,int key){ if (root==null)return false; if (find(root.left,s,key))return true; if (s.contains(key-root.val))return true; else s.add(root.val); return find(root.right,s,key); } public boolean findTarget(TreeNode root, int k) { HashSet<Integer> s= new HashSet<>(); return find(root,s,k); } public static void main(String[] args) { FastScanner sc = new FastScanner(); // Scanner sc = new Scanner(System.in); int t=sc.nextInt(); while (t-->=1){ int n=sc.nextInt(); int a[]=sc.readArray(n); sort(a); long ans=0,min=0; for (int i=1;i<n;i++){ long diff=a[i]-a[i-1]; diff*=-1; min+=(diff*i); ans+=min; } ans+=a[n-1]; System.out.println(ans); } } // out.flush(); //------------------------------------if------------------------------------------------------------------------------------------------------------------------------------------------- //sieve static void primeSieve(int a[]){ //mark all odd number as prime for (int i=3;i<a.length;i+=2){ a[i]=1; } for (long i=3;i<a.length;i+=2){ //if the number is marked then it is prime if (a[(int) i]==1){ //mark all muliple of the number as not prime for (long j=i*i;j<a.length;j+=i){ a[(int)j]=0; } } } a[2]=1; a[1]=a[0]=0; } //prime static boolean isPrime(int n){ if (n==2)return true; if (n==1)return false; for (int i=2;i*i<=n;i++){ if (n%i==0)return false; } return true; } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static String sortString(String s) { char temp[] = s.toCharArray(); Arrays.sort(temp); return new String(temp); } static class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // to sort first part public int compareTo(Pair other) { if (this.a == other.a) return other.b >=this.b ? -1 : 1; else if (this.a < other.a) return 1; else return -1; } // public int compareTo(Pair other) { // if (this.b == other.b){ // if (this.a> other.a)return 1; // else return -1; // } // if (this.b > other.b) return 1; // else return -1; // } //sort on the basis of first part only // public int compareTo(Pair other) { // if (this.a == other.a) return 0; // if (this.a > other.a) return 1; // else return -1; // } } static int[] frequency(String s){ int fre[]= new int[26]; for (int i=0;i<s.length();i++){ fre[s.charAt(i)-'a']++; } return fre; } static long LOWERBOUND(long a[],long k){ int s=0,e=a.length-1; long ans=-1; while (s<=e){ int mid=(s+e)/2; if (a[mid]<=k){ ans=mid; s=mid+1; } else { e=mid-1; } } return ans; } static long mod =(long)(1e9+7); static long mod(long x) { return ((x % mod + mod) % mod); } static long div(long a,long b){ return ((a/b)%mod+mod)%mod; } static long add(long x, long y) { return mod(mod(x) + mod(y)); } static long mul(long x, long y) { return mod(mod(x) * mod(y)); } //Fast Power(logN) static int fastPower(long a,long n){ int ans=1; while (n>0){ long lastBit=n&1; if (lastBit==1){ ans=(int)mul(ans,a); } a=(int)mul(a,a); n>>=1; } return ans; } static int[] find(int n, int start, int diff) { int a[] = new int[n]; a[0] = start; for (int i = 1; i < n; i++) a[i] = a[i - 1] + diff; return a; } static void swap(int a, int b) { int c = a; a = b; b = c; } static void printArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } static boolean sorted(int a[]) { int n = a.length; boolean flag = true; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) flag = false; } if (flag) return true; else return false; } public static int findlog(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if (den == 0) return 0; return (int) (num / den); } public static long gcd(long a, long b) { if (b % a == 0) return a; return gcd(b % a, a); } public static int gcdInt(int a, int b) { if (b % a == 0) return a; return gcdInt(b % a, a); } static void sortReverse(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); // Collections.sort.(l); Collections.sort(l, Collections.reverseOrder()); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble(){ return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArrayLong(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } double[] readArrayDouble(long n) { double[] a = new double[(int) n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
4c6728e00d606d107973d8763670705e
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-->=1){ int n=sc.nextInt(); long a[]=sc.readArrayLong(n); Arrays.sort(a); long sum1=0; long sum2=0; for (int i=2;i<n;i++){ sum2+=a[i-2]; sum1-=(a[i]*(i-1)); sum1+=sum2; } System.out.println(sum1); } } // out.flush(); //------------------------------------if------------------------------------------------------------------------------------------------------------------------------------------------- //sieve static void primeSieve(int a[]){ //mark all odd number as prime for (int i=3;i<a.length;i+=2){ a[i]=1; } for (long i=3;i<a.length;i+=2){ //if the number is marked then it is prime if (a[(int) i]==1){ //mark all muliple of the number as not prime for (long j=i*i;j<a.length;j+=i){ a[(int)j]=0; } } } a[2]=1; a[1]=a[0]=0; } //prime static boolean isPrime(int n){ if (n==2)return true; if (n==1)return false; for (int i=2;i*i<=n;i++){ if (n%i==0)return false; } return true; } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static String sortString(String s) { char temp[] = s.toCharArray(); Arrays.sort(temp); return new String(temp); } static class Pair implements Comparable<Pair> { int a; int b; public Pair(int a, int b) { this.a = a; this.b = b; } // to sort first part public int compareTo(Pair other) { if (this.a == other.a) return other.b > this.b ? -1 : 1; else if (this.a > other.a) return 1; else return -1; } // public int compareTo(Pair other) { // if (this.b == other.b){ // if (this.a> other.a)return 1; // else return -1; // } // if (this.b > other.b) return 1; // else return -1; // } //sort on the basis of first part only // public int compareTo(Pair other) { // if (this.a == other.a) return 0; // if (this.a > other.a) return 1; // else return -1; // } } static int[] frequency(String s){ int fre[]= new int[26]; for (int i=0;i<s.length();i++){ fre[s.charAt(i)-'a']++; } return fre; } static long LOWERBOUND(long a[],long k){ int s=0,e=a.length-1; long ans=-1; while (s<=e){ int mid=(s+e)/2; if (a[mid]<=k){ ans=mid; s=mid+1; } else { e=mid-1; } } return ans; } static long mod =(long)(1e9+7); static long mod(long x) { return ((x % mod + mod) % mod); } static long div(long a,long b){ return ((a/b)%mod+mod)%mod; } static long add(long x, long y) { return mod(mod(x) + mod(y)); } static long mul(long x, long y) { return mod(mod(x) * mod(y)); } //Fast Power(logN) static int fastPower(long a,long n){ int ans=1; while (n>0){ long lastBit=n&1; if (lastBit==1){ ans=(int)mul(ans,a); } a=(int)mul(a,a); n>>=1; } return ans; } static int[] find(int n, int start, int diff) { int a[] = new int[n]; a[0] = start; for (int i = 1; i < n; i++) a[i] = a[i - 1] + diff; return a; } static void swap(int a, int b) { int c = a; a = b; b = c; } static void printArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } static boolean sorted(int a[]) { int n = a.length; boolean flag = true; for (int i = 0; i < n - 1; i++) { if (a[i] > a[i + 1]) flag = false; } if (flag) return true; else return false; } public static int findlog(long n) { if (n == 0) return 0; if (n == 1) return 0; if (n == 2) return 1; double num = Math.log(n); double den = Math.log(2); if (den == 0) return 0; return (int) (num / den); } public static long gcd(long a, long b) { if (b % a == 0) return a; return gcd(b % a, a); } public static int gcdInt(int a, int b) { if (b % a == 0) return a; return gcdInt(b % a, a); } static void sortReverse(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); // Collections.sort.(l); Collections.sort(l, Collections.reverseOrder()); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble(){ return Double.parseDouble(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] readArrayLong(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } double[] readArrayDouble(long n) { double[] a = new double[(int) n]; for (int i = 0; i < n; i++) a[i] = nextDouble(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
591c723999e91d32889a4d0b5d13dd24
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class _practise { 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()); } int[] ia(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=nextInt(); return a; } int[][] ia(int n , int m) { int a[][]=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<n ;j++) a[i][j]=nextInt(); return a; } char[][] ca(int n , int m) { char a[][]=new char[n][m]; for(int i=0;i<n;i++) { String x =next(); for(int j=0;j<n ;j++) a[i][j]=x.charAt(j); } return a; } long[] la(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void sort(long[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {long oi=r.nextInt(n), temp=a[i];a[i]=a[(int)oi];a[(int)oi]=temp;}Arrays.sort(a);} static void sort(int[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {int oi=r.nextInt(n), temp=a[i];a[i]=a[oi];a[oi]=temp;}Arrays.sort(a);} public static long sum(long a[]) {long sum=0; for(long i : a) sum+=i; return(sum);} public static long count(long a[] , long x) {long c=0; for(long i : a) if(i==x) c++; return(c);} public static int sum(int a[]) { int sum=0; for(int i : a) sum+=i; return(sum);} public static int count(int a[] ,int x) {int c=0; for(int i : a) if(i==x) c++; return(c);} public static int count(String s ,char ch) {int c=0; char x[] = s.toCharArray(); for(char i : x) if(ch==i) c++; return(c);} public static boolean prime(int n) {for(int i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static boolean prime(long n) {for(long i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static int gcd(int n1, int n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static long gcd(long n1, long n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static int[] freq(int a[], int n) { int f[]=new int[n+1]; for(int i:a) f[i]++; return f;} public static int[] pos(int a[], int n) { int f[]=new int[n+1]; for(int i=0; i<n ;i++) f[a[i]]=i; return f;} public static long mindig(long n) { long ans=9; while(n>0) { if(n%10<ans) ans=n%10; n/=10; } return ans; } public static long maxdig(long n) { long ans=0; while(n>0) { if(n%10>ans) ans=n%10; n/=10; } return ans; } public static boolean palin(String s) { StringBuilder sb = new StringBuilder(); sb.append(s); String str=String.valueOf(sb.reverse()); if(s.equals(str)) return true; else return false; } public static void main(String args[]) { FastReader in=new FastReader(); PrintWriter so = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); _practise ob = new _practise(); int t = in.nextInt(); //int t = 1; while(t-->0) { int n = in.nextInt(); long a[] = in.la(n); sort(a); long ans=a[n-1],prev=0; for(int i=1 ; i<n ; i++) { prev=prev+i*(a[i]-a[i-1]); ans-=prev; } so.println(ans); } so.flush(); /*String s = in.next(); * Arrays.stream(f).min().getAsInt() * BigInteger f = new BigInteger("1"); 1 ke jagah koi bhi value ho skta jo aap * initial value banan chahte int a[] = new int[n]; Stack<Integer> stack = new Stack<Integer>(); Deque<Integer> q = new LinkedList<>(); or Deque<Integer> q = new ArrayDeque<Integer>(); PriorityQueue<Long> pq = new PriorityQueue<Long>(); ArrayList<Integer> al = new ArrayList<Integer>(); StringBuilder sb = new StringBuilder(); HashSet<Integer> st = new LinkedHashSet<Integer>(); Set<Integer> s = new HashSet<Integer>(); Map<Long,Integer> hm = new HashMap<Long, Integer>(); //<key,value> for(Map.Entry<Integer, Integer> i :hm.entrySet()) HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); so.println("HELLO"); Arrays.sort(a,Comparator.comparingDouble(o->o[0])) Arrays.sort(a, (aa, bb) -> Integer.compare(aa[1], bb[1]));*/ } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
3337063aa0bd623e58aa7b0c76a00089
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class _practise { 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()); } int[] ia(int n) { int a[]=new int[n]; for(int i=0;i<n;i++)a[i]=nextInt(); return a; } int[][] ia(int n , int m) { int a[][]=new int[n][m]; for(int i=0;i<n;i++) for(int j=0;j<n ;j++) a[i][j]=nextInt(); return a; } char[][] ca(int n , int m) { char a[][]=new char[n][m]; for(int i=0;i<n;i++) { String x =next(); for(int j=0;j<n ;j++) a[i][j]=x.charAt(j); } return a; } long[] la(int n) { long a[]=new long[n]; for(int i=0;i<n;i++)a[i]=nextLong(); return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static void sort(long[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {long oi=r.nextInt(n), temp=a[i];a[i]=a[(int)oi];a[(int)oi]=temp;}Arrays.sort(a);} static void sort(int[] a) {int n=a.length;Random r=new Random();for (int i=0; i<a.length; i++) {int oi=r.nextInt(n), temp=a[i];a[i]=a[oi];a[oi]=temp;}Arrays.sort(a);} public static long sum(long a[]) {long sum=0; for(long i : a) sum+=i; return(sum);} public static long count(long a[] , long x) {long c=0; for(long i : a) if(i==x) c++; return(c);} public static int sum(int a[]) { int sum=0; for(int i : a) sum+=i; return(sum);} public static int count(int a[] ,int x) {int c=0; for(int i : a) if(i==x) c++; return(c);} public static int count(String s ,char ch) {int c=0; char x[] = s.toCharArray(); for(char i : x) if(ch==i) c++; return(c);} public static boolean prime(int n) {for(int i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static boolean prime(long n) {for(long i=2 ; i<=Math.sqrt(n) ; i++) if(n%i==0) return false; return true;} public static int gcd(int n1, int n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static long gcd(long n1, long n2) { if (n2 != 0)return gcd(n2, n1 % n2); else return n1;} public static int[] freq(int a[], int n) { int f[]=new int[n+1]; for(int i:a) f[i]++; return f;} public static int[] pos(int a[], int n) { int f[]=new int[n+1]; for(int i=0; i<n ;i++) f[a[i]]=i; return f;} public static long mindig(long n) { long ans=9; while(n>0) { if(n%10<ans) ans=n%10; n/=10; } return ans; } public static long maxdig(long n) { long ans=0; while(n>0) { if(n%10>ans) ans=n%10; n/=10; } return ans; } public static boolean palin(String s) { StringBuilder sb = new StringBuilder(); sb.append(s); String str=String.valueOf(sb.reverse()); if(s.equals(str)) return true; else return false; } public static void main(String args[]) { FastReader in=new FastReader(); PrintWriter so = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); _practise ob = new _practise(); int t = in.nextInt(); //int t = 1; while(t-->0) { int n = in.nextInt(); long a[] = in.la(n); sort(a); long ans=0,x=0; for(int i=1 ; i<n ; i++) { ans+=a[i]-a[i-1]; ans-=a[i]; long c = ((i-1)*a[i])-x; ans-=c; x+=a[i]; } so.println(ans); } so.flush(); /*String s = in.next(); * Arrays.stream(f).min().getAsInt() * BigInteger f = new BigInteger("1"); 1 ke jagah koi bhi value ho skta jo aap * initial value banan chahte int a[] = new int[n]; Stack<Integer> stack = new Stack<Integer>(); Deque<Integer> q = new LinkedList<>(); or Deque<Integer> q = new ArrayDeque<Integer>(); PriorityQueue<Long> pq = new PriorityQueue<Long>(); ArrayList<Integer> al = new ArrayList<Integer>(); StringBuilder sb = new StringBuilder(); HashSet<Integer> st = new LinkedHashSet<Integer>(); Set<Integer> s = new HashSet<Integer>(); Map<Long,Integer> hm = new HashMap<Long, Integer>(); //<key,value> for(Map.Entry<Integer, Integer> i :hm.entrySet()) HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>(); so.println("HELLO"); Arrays.sort(a,Comparator.comparingDouble(o->o[0])) Arrays.sort(a, (aa, bb) -> Integer.compare(aa[1], bb[1]));*/ } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
175117bf4baf0d0e93d6eb8123d201dd
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package cp; import java.util.*; import static java.lang.Math.min; import static java.lang.Math.abs; import static java.lang.Math.max; import java.io.*; public class EdE { static long[] mods = {1000000007, 998244353, 1000000009}; static long mod = mods[0]; public static MyScanner in; public static PrintWriter out; static int[][] dp; static ArrayList<ArrayList<Integer>> tree; public static void main( String[] args ) throws IOException{ in = new MyScanner(); out = new PrintWriter(System.out); StringBuilder ans1=new StringBuilder(); int test=in.nextInt(); while(test-->0) { int n=in.nextInt(); long a[]=readArrayLong(n); long ans=0; Arrays.sort(a); ans+=a[n-1]; long[] left=new long[n]; for(int i=1;i<n;i++) { left[i]=left[i-1]+i*(a[i]-a[i-1]); ans-=left[i]; } ans1.append(ans).append(System.getProperty("line.separator")); } out.println(ans1); out.close(); } //comparator to solve according to b in descending order static class Pair implements Comparable<Pair>{ private long a; private long b; public Pair(long a, long b) { this.a = a; this.b = b; } public int compareTo(Pair other) { return Long.compare(this.b, other.b ); //to sort in ascending order swap the arguments in Long.compare //return Long.compare(other.b ,this.b); //to sort in descending order swap the arguments in Long.compare } } static void printArray(long[] a) { StringBuilder stringBuilder=new StringBuilder(); for(long i: a) stringBuilder.append(i).append(" "); out.println(stringBuilder); } public static void sort(long[] array){ ArrayList<Long> copy = new ArrayList<>(); for (long i : array) copy.add(i); Collections.sort(copy); for(int i = 0;i<array.length;i++) array[i] = copy.get(i); } public static void sortDes(long[] array){ ArrayList<Long> copy = new ArrayList<>(); for (long i : array) copy.add(i); Collections.sort(copy); int j=array.length-1; for(int i = 0;i<array.length;i++) array[j--] = copy.get(i); } static String[] readArrayString(int n){ String[] array = new String[n]; for(int j =0 ;j<n;j++) array[j] = in.next(); return array; } static int[] readArrayInt(int n){ int[] array = new int[n]; for(int j = 0;j<n;j++) array[j] = in.nextInt(); return array; } static int[] readArrayInt1(int n){ int[] array = new int[n+1]; for(int j = 1;j<=n;j++){ array[j] = in.nextInt(); } return array; } static long[] readArrayLong(int n){ long[] array = new long[n]; for(int j =0 ;j<n;j++) array[j] = in.nextLong(); return array; } static double[] readArrayDouble(int n){ double[] array = new double[n]; for(int j =0 ;j<n;j++) array[j] = in.nextDouble(); return array; } static int minIndex(int[] array){ int minValue = Integer.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(long[] array){ long minValue = Long.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static int minIndex(double[] array){ double minValue = Double.MAX_VALUE; int minIndex = -1; for(int j = 0;j<array.length;j++){ if (array[j] < minValue){ minValue = array[j]; minIndex = j; } } return minIndex; } static long power(long x, long y){ if (y == 0) return 1; if (y%2 == 1) return (x*power(x, y-1))%mod; return power((x*x)%mod, y/2)%mod; } static void verdict(boolean a){ out.println(a ? "YES" : "NO"); } 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\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
7e15291a0fbbbe4f371ed0039798475d
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { FastScanner f = new FastScanner(); int ttt=1; ttt=f.nextInt(); PrintWriter out=new PrintWriter(System.out); outer:for(int tt=0;tt<ttt;tt++) { int n=f.nextInt(); int[] l=f.readArray(n); long[] pref=new long[n]; sort(l); for(int i=1;i<n;i++) pref[i]=l[i]+pref[i-1]; long ans=0; // System.out.println(Arrays.toString(pref)); for(int i=2;i<n;i++) { ans+=((i-1)*1L*l[i]-pref[i-2]); // System.out.println((i-1)*l[i]+" "+pref[i-2]); } System.out.println(-ans); } out.close(); } static void sort(int[] p) { ArrayList<Integer> q = new ArrayList<>(); for (int i: p) q.add( i); Collections.sort(q); for (int i = 0; i < p.length; i++) p[i] = q.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } long[] readLongArray(int n) { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
1aabbf3123a16e168b293023e4d9e977
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int[] d=new int[n]; for(int i=0;i<n;i++) d[i]=sc.nextInt(); Arrays.sort(d); long cost=0; long[] pre=new long[n]; for(int i=1;i<n;i++) pre[i]=0l+pre[i-1]+d[i]; for(int i=0;i<n;i++) cost+=(i+1)*1l*(d[i])-pre[i]; cost-=d[n-1]; System.out.println(-cost); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
14bf88c7c0721e707b73984d20eccbb9
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package pack; import java.io.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.io.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.*; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; import java.math.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.sqrt; import static java.lang.Math.floor; public class topcoder { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } static int depth(TreeNode root) { if(root == null)return 0; int a = 1+ depth(root.left); int b = 1+ depth(root.right); return Math.max(a,b); } static HashSet<Integer>set = new HashSet<>(); static void deepestLeaves(TreeNode root, int cur_depth, int depth) { if(root == null)return; if(cur_depth == depth)set.add(root.val); deepestLeaves(root.left,cur_depth+1,depth); deepestLeaves(root.right,cur_depth+1,depth); } public static void print(TreeNode root) { if(root == null)return; System.out.print(root.val+" "); System.out.println("er"); print(root.left); print(root.right); } public static HashSet<Integer>original(TreeNode root){ int d = depth(root); deepestLeaves(root,0,d); return set; } static HashSet<Integer>set1 = new HashSet<>(); static void leaves(TreeNode root) { if(root == null)return; if(root.left == null && root.right == null)set1.add(root.val); leaves(root.left); leaves(root.right); } public static boolean check(HashSet<Integer>s, HashSet<Integer>s1) { if(s.size() != s1.size())return false; for(int a : s) { if(!s1.contains(a))return false; } return true; } static TreeNode subTree; public static void smallest_subTree(TreeNode root) { if(root == null)return; smallest_subTree(root.left); smallest_subTree(root.right); set1 = new HashSet<>(); leaves(root); boolean smallest = check(set,set1); if(smallest) { subTree = root; return; } } public static TreeNode answer(TreeNode root) { smallest_subTree(root); return subTree; } } static class pair{ int first; int second; public pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(pair p) { if(first == p.first)return second-p.second; return first-p.first; } } static class Compare{ static void compare(ArrayList<pair>arr, long n) { Collections.sort(arr,new Comparator<pair>() { public int compare(pair p1, pair p2) { return (int) (p1.first-p2.first); } }); } } public static HashMap<Integer,Integer>sortByValue(HashMap<Integer,Integer>hm){ List<Map.Entry<Integer,Integer>>list = new LinkedList<Map.Entry<Integer,Integer>>(hm.entrySet()); Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>(){ public int compare(Map.Entry<Integer,Integer>o1, Map.Entry<Integer,Integer>o2) { return (o1.getValue()).compareTo(o2.getValue()); }}); HashMap<Integer,Integer>temp = new LinkedHashMap<Integer,Integer>(); for(Map.Entry<Integer,Integer>aa : list) { temp.put(aa.getKey(), aa.getValue()); } return temp; } static class pairr implements Comparable<pairr>{ static Long value; Long index; public pairr(Long value, Long index) { this.value = value; this.index = index; } public int compareTo(pairr o) { return (int)(value-o.value); } } static class Key<K1, K2> { public K1 key1; public K2 key2; public Key(K1 key1, K2 key2) { this.key1 = key1; this.key2 = key2; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; if (key1 != null ? !key1.equals(key.key1) : key.key1 != null) { return false; } if (key2 != null ? !key2.equals(key.key2) : key.key2 != null) { return false; } return true; } @Override public int hashCode() { int result = key1 != null ? key1.hashCode() : 0; result = 31 * result + (key2 != null ? key2.hashCode() : 0); return result; } @Override public String toString() { return "[" + key1 + ", " + key2 + "]"; } } public static int sumOfDigits (long n) { int sum = 0; while(n > 0) { sum += n%10; n /= 10; } return sum; } public static long binary_search(int s, int e, long num, long []ar) { if(s > e) { return -1; } int mid = (s+e)/2; if(s == e && ar[s] >= num) { return ar[s]; }else if(s == e && ar[s] < num) { return -1; }else if(ar[mid] < num) { return binary_search(mid+1,e,num,ar); }else if(ar[mid] >= num) { return binary_search(s,mid,num,ar); } return -1; } public static int index_search(int s, int e, long num, long []ar) { if(s > e) { return -1; } int mid = (s+e)/2; if(s == e && ar[s] >= num) { return s; }else if(s == e && ar[s] < num) { return -1; }else if(ar[mid] < num) { return index_search(mid+1,e,num,ar); }else if(ar[mid] >= num) { return index_search(s,mid,num,ar); } return -1; } public static void swap(int []ar, int i, int j) { for(int k= j; k >= i; k--) { int temp = ar[k]; ar[k] = ar[k+1]; ar[k+1] = temp; } } public static boolean digit_exists(long n) { while(n > 0) { if(n%10 == 9) return true; n = n/10; } return false; } public static int log(int n) { int c = 0; while(n > 0) { c++; n /=2; } return c; } public static int findOr(int[]bits){ int or=0; for(int i=0;i<32;i++){ or=or<<1; if(bits[i]>0) or=or+1; } return or; } static void simpleSieve(int limit, Vector<Integer> prime) { // Create a boolean array "mark[0..n-1]" and initialize // all entries of it as true. A value in mark[p] will // finally be false if 'p' is Not a prime, else true. boolean mark[] = new boolean[limit+1]; for (int i = 0; i < mark.length; i++) mark[i] = true; for (int p=2; p*p<limit; p++) { // If p is not changed, then it is a prime if (mark[p] == true) { // Update all multiples of p for (int i=p*p; i<limit; i+=p) mark[i] = false; } } // Print all prime numbers and store them in prime for (int p=2; p<limit; p++) { if (mark[p] == true) { prime.add(p); } } } // Prints all prime numbers smaller than 'n' public static void segmentedSieve(int n, ArrayList<Integer>l) { // Compute all primes smaller than or equal // to square root of n using simple sieve int limit = (int) (floor(sqrt(n))+1); Vector<Integer> prime = new Vector<>(); simpleSieve(limit, prime); // Divide the range [0..n-1] in different segments // We have chosen segment size as sqrt(n). int low = limit; int high = 2*limit; // While all segments of range [0..n-1] are not processed, // process one segment at a time while (low < n) { if (high >= n) high = n; // To mark primes in current range. A value in mark[i] // will finally be false if 'i-low' is Not a prime, // else true. boolean mark[] = new boolean[limit+1]; for (int i = 0; i < mark.length; i++) mark[i] = true; // Use the found primes by simpleSieve() to find // primes in current range for (int i = 0; i < prime.size(); i++) { // Find the minimum number in [low..high] that is // a multiple of prime.get(i) (divisible by prime.get(i)) // For example, if low is 31 and prime.get(i) is 3, // we start with 33. int loLim = (int) (floor(low/prime.get(i)) * prime.get(i)); if (loLim < low) loLim += prime.get(i); /* Mark multiples of prime.get(i) in [low..high]: We are marking j - low for j, i.e. each number in range [low, high] is mapped to [0, high-low] so if range is [50, 100] marking 50 corresponds to marking 0, marking 51 corresponds to 1 and so on. In this way we need to allocate space only for range */ for (int j=loLim; j<high; j+=prime.get(i)) mark[j-low] = false; } // Numbers which are not marked as false are prime for (int i = low; i<high; i++) if (mark[i - low] == true) l.add(i); // Update low and high for next segment low = low + limit; high = high + limit; } } public static int find_indexNum(long k) { long k1 = k; int power = 0; while(k > 0) { power++; k /=2 ; } long check = (long)Math.pow(2, power-1); if(k1 == check) { return power; } // System.out.println(power); long f = (long)Math.pow(2, power-1); long rem = k1-f; return find_indexNum(rem); } public static void sortPair(ArrayList<pair>l, int n) { n = l.size(); Compare obj = new Compare(); obj.compare(l, n); } public static void shuffle(int []array, int num,int t_index, boolean []vis, int m ) { for(int i = 0; i < m; i++) { if(vis[i] == false) { int temp = array[i]; if(i < t_index) { vis[i] = true; } array[i] = num; array[t_index] = temp; // System.out.println(array[t_index]+" "+array[i]); break; } } } public static void rotate(int []arr,int j, int times, int m) { if(j == 0) { int temp1 = arr[0]; arr[0] = arr[times]; arr[times] = temp1; }else { int temp = arr[j]; int z = arr[0]; arr[0] = arr[times]; arr[j] = z; arr[times] = temp; } } public static void recur(int i,int A, int B,int []dp,int []metal, int n, boolean took,int ind) { if(i-A <= 0 && i-B <= 0)return; int count = 0; for(int j = 1; j <= n; j++) { if(dp[j] >= metal[j]) { count++; } } if(count == n)return; if(i-A >= 0 && i-B >= 0 && dp[i] > 0 && dp[i] > metal[i]) { dp[i]--; dp[i-A]++; dp[i-B]++; } if(ind == 6) { // System.out.println(Arrays.toString(dp)); } recur(i-A,A,B,dp,metal,n,took,ind); recur(i-B,A,B,dp,metal,n,took,ind); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static boolean[] getSieve(int n) { boolean[] isPrime = new boolean[n+1]; for (int i = 2; i <= n; i++) isPrime[i] = true; for (int i = 2; i*i <= n; i++) if (isPrime[i]) for (int j = i; i*j <= n; j++) isPrime[i*j] = false; return isPrime; } static int gcd(int a, int b) { if(a == 0) return b; return gcd(b%a,a); } public static void dfs(LinkedList<Integer>[]list, HashMap<Integer,Integer>map, int parent, int n) { Stack<Integer>st = new Stack<>(); } public static boolean pos(int n) { int i = 1; boolean pos = false; while(i*i <= n) { if(i*i*2 == n || i*i*4 == n) { pos = true; break; } i++; } if(pos)return true; return false; } static long count = 0; public static void pairs (int []ar, int s, int e) { if(e <= s)return; // System.out.println(ar[s]+" "+ar[e]+" "+s+" "+e); if(ar[e]-ar[s] == e-s) { count++; //System.out.println("sdf"); } pairs(ar,s+1,e); pairs(ar,s,e-1); } public static long ways(long n) { return (n*(n-1))/2; } static boolean isPrime(long n) { if(n <= 1)return false; if(n <= 3)return true; if(n%2 == 0 || n%3 == 0)return false; for(int i = 5; i*i <= n; i+= 6) { if(n%i == 0 || n%(i+2) == 0) return false; } return true; } static long nextPrime(long n) { boolean found = false; long prime = n; while(!found) { prime++; if(isPrime(prime)) found = true; } return prime; } public static boolean isValid(int h, int m, int hour, int minute) { int a = flip(hour / 10); if (a == -1) return false; int b = flip(hour % 10); if (b == -1) return false; int c = flip(minute / 10); if (c == -1) return false; int d = flip(minute % 10); if (d == -1) return false; if (10 * d + c >= h) return false; if (10 * b + a >= m) return false; return true; } public static int flip(int x) { if (x == 0) return 0; if (x == 1) return 1; if (x == 2) return 5; if (x == 5) return 2; if (x == 8) return 8; return -1; } static long maximum(long a, long b, long c, long d) { long m = Math.max(a, b); long m1 = Math.max(c, d); return Math.max(m1, m1); } static long minimum(long a, long b, long c,long d) { long m = Math.min(a, b); long m1 = Math.min(c, d); return Math.min(m, m1); } static long ans = 0; public static void solve1(boolean [][]vis,long [][]mat, int r, int c, int r2, int c2, int r1, int c1, int r3, int c3) { if(r > r1 || c > c1 || r > r2 || c > c2 || r1 > r3 || c1 > c3 || r3 < r2 || c3 < c2 || vis[r][c] || vis[r1][c1]|| vis[r2][c2] || vis[r3][c3]) return; vis[r][c] = true; vis[r1][c1] = true; vis[r2][c2] = true; vis[r3][c3] = true; long max = maximum(mat[r][c],mat[r1][c1],mat[r2][c2],mat[r3][c3]); long min = minimum(mat[r][c],mat[r1][c1],mat[r2][c2],mat[r3][c3]); long a = mat[r][c]; long b = mat[r1][c1]; long c4 = mat[r2][c2]; long d =mat[r3][c3]; long []p = {a,b,c4,d}; Arrays.sort(p); long temp = (p[2]+p[3]-p[0]-p[1]); if(r == r1 && r == r2 && r2 == r3 && r1 == r3) temp /= 2; System.out.println(Arrays.toString(p)); ans += temp; solve1(vis,mat,r+1,c,r2+1,c2,r1-1,c1,r3-1,c3); solve1(vis,mat,r,c+1,r2,c2-1,r1,c1+1,r3,c3-1); solve1 (vis,mat,r+1,c+1,r2+1,c2-1,r1-1,c1+1,r3-1,c3-1); } private static int solve(int[][] mat, int i, int c, int j, int c2, int k, int c1, int l, int c3) { // TODO Auto-generated method stub return 0; } public static int dfs(int parent, LinkedList<Integer>[]list) { for(int i : list[parent]) { if(list[parent].size() == 0) { return 0; }else { return 1 + dfs(i,list); } } return 0; } public static long answer = Integer.MAX_VALUE; public static void min_Time(int [][]dp, int i, HashSet<Integer>set, int min, int r, int c) { if(i > r) { answer = Math.min(answer, min); return; } if(min > answer)return; for(int j = i; j <= c; j++) { if(!set.contains(j)) { set.add(j); min += dp[i][j]; min_Time(dp,i+1,set,min,r,c); min -= dp[i][j]; set.remove(j); } } } public static void dp(int [][]dp, int r, int c, int o, int z, long sum) { if(r > o) { answer = Math.min(answer, sum); } if(r > o || c > z) { return; } if(sum > answer)return; sum += dp[r][c]; dp(dp,r+1,c+1,o,z,sum); sum -= dp[r][c]; dp(dp,r,c+1,o,z,sum); } static HashSet<ArrayList<Integer>>l = new HashSet<>(); public static void fourSum(Deque<Integer>ll, int i, int target, int []ar, int n) { if(ll.size() == 4) { int sum = 0; ArrayList<Integer>list = new ArrayList<>(); for(int a : ll) { sum += a; list.add(a); } if(sum == target) { Collections.sort(list); l.add(list); // System.out.println(ll); } return; } for(int j = i; j < n; j++) { ll.add(ar[j]); fourSum(ll,j+1,target,ar,n); ll.removeLast(); } } static int max_bottles(int cur, int exchange, int n){ if(cur == exchange){ cur = 0; n++; } if(n == 0)return 0; return 1+ max_bottles(cur+1,exchange,n-1); } public static void fill(int [][]mat, List<Integer>ans, int row_start, int row_end, int col_start, int col_end) { for(int i = col_start; i <= col_end; i++) { ans.add(mat[row_start][i]); } for(int i = row_start+1; i <= row_end; i++) { ans.add(mat[i][col_end]); } if(col_start == col_end)return; if(row_start == row_end)return; for(int i = col_end-1; i >= col_start; i--) { ans.add(mat[row_end][i]); } for(int i = row_end-1; i >= row_start+1; i--) { ans.add(mat[i][col_start]); } } public static void create(int [][]mat, int j, int i, int k) { if(i < 1 || j >= mat.length)return; mat[j][i] = k; create(mat,j+1,i-1,k+1); } public static long sum(int [][]mat, int x1, int y1, int x2, int y2) { long sum = 0; while(x1 <= x2) { sum += mat[x1][y1]; // System.out.println(mat[x1][y1]); x1++; } y1++; while(y1 <= y2) { sum += mat[x2][y1]; y1++; } return sum; } public static boolean allneg(int []ar, int n) { for(int i = 0; i < n; i++) { if(ar[i] >= 0)return false; } return true; } public static boolean allpos(int []ar, int n) { for(int i = 0; i < n; i++) { if(ar[i] <= 0)return false; } return true; } public static int max_pos(int []ar, int n) { int min = Integer.MAX_VALUE; for(int i = 1; i < n; i++) { if(ar[i] > 0) { break; } int a = Math.abs(ar[i]-ar[i-1]); min = Math.min(min, a); } int c = 0; boolean zero = false; TreeSet<Integer>set = new TreeSet<>(); int neg = 0; for(int i = 0; i < n; i++) { if(ar[i] <= 0) {neg++; if(ar[i] == 0) zero = true; continue;} if(ar[i] <= min) { c = 1; } } neg += c; return neg; } static final int MAX = 10000000; // prefix[i] is going to store count // of primes till i (including i). static int prefix[] = new int[MAX + 1]; static void buildPrefix() { // Create a boolean array "prime[0..n]". A // value in prime[i] will finally be false // if i is Not a prime, else true. boolean prime[] = new boolean[MAX + 1]; Arrays.fill(prime, true); for (int p = 2; p * p <= MAX; p++) { // If prime[p] is not changed, then // it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= MAX; i += p) prime[i] = false; } } // Build prefix array prefix[0] = prefix[1] = 0; for (int p = 2; p <= MAX; p++) { prefix[p] = prefix[p - 1]; if (prime[p]) prefix[p]++; } } static int query(int L, int R) { return prefix[R] - prefix[L - 1]; } static void alter(int n) { int ans = 0; boolean []vis = new boolean[n+1]; for(int i = 2; i <= n; i++){ boolean p = false; if(vis[i] == false) { for(int j = i; j <= n; j+=i) { if(vis[j] == true) { p = true; }else { vis[j] = true; } } if(!p)ans++; } } System.out.println(ans); } public static void solveDK(int []dp, int i, int D, int K) { int d = D/K; int ans = -1; int ind = d+1; while(ind < i) { int temp = i/ind; temp--; if(dp[temp*ind] == temp) { ans = dp[temp*ind]+1; dp[i] = ans; break; } ind = ind*2; } if(ans == -1) dp[i] = 1; } public static void solveKD(int []dp, int i, int D, int K) { int d = K/D; int ans = -1; int ind = d+1; while(ind < i) { int temp = i/ind; temp--; if(dp[temp*ind] == temp) { ans = dp[temp*ind]+1; dp[i] = ans; break; } ind = ind*2; } if(ans == -1) dp[i] = 1; } static int countGreater(int arr[], int n, int k) { int l = 0; int r = n - 1; // Stores the index of the left most element // from the array which is greater than k int leftGreater = n; // Finds number of elements greater than k while (l <= r) { int m = l + (r - l) / 2; // If mid element is greater than // k update leftGreater and r if (arr[m] > k) { leftGreater = m; r = m - 1; } // If mid element is less than // or equal to k update l else l = m + 1; } // Return the count of elements greater than k return (n - leftGreater); } static ArrayList<Integer>printDivisors(int n) { // Note that this loop runs till square root ArrayList<Integer>list = new ArrayList<>(); for (int i=1; i<=Math.sqrt(n); i++) { if (n%i==0) { // If divisors are equal, print only one if (n/i == i) list.add(i); else // Otherwise print both list.add(i); list.add(n/i); } } return list; } static ArrayList<List<Integer>>res = new ArrayList<>(); static void sum(int []ar, ArrayList<Integer>list,int target, int j) { int sum = 0; for(int a : list) { sum += a; } if(sum == target) { res.add(new ArrayList(list)); return; }else if(sum > target) return; for(int i = j; i < ar.length; i++) { list.add(ar[i]); sum(ar,list,target,i); list.remove(list.size()-1); } } public static void main(String args[])throws IOException{ // System.setIn(new FileInputStream("Case.txt")); BufferedReader ob = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); int t = Integer.parseInt(ob.readLine()); while(t --> 0) { int n = Integer.parseInt(ob.readLine()); Long []ar = new Long[n]; StringTokenizer st = new StringTokenizer(ob.readLine()); Long total = 0L; for(int i = 0; i < n; i++) { ar[i] = Long.parseLong(st.nextToken()); } Arrays.sort(ar); Long countMax = Long.MIN_VALUE; Long count = 1L; for(int i = n-1; i >= 1; i--) { if(ar[i] == ar[i-1]) { count++; }else { if(count > countMax) { countMax = count; total += ar[i]*count; } count = 1L; } } Long sum = 0L; Long weight = 0L; for(int i = 1; i < n; i++) { weight += (ar[i]*i)-sum; sum += ar[i]; } weight *= -1; weight += total; System.out.println(weight); } } static class pairrr implements Comparable<pairrr> { int x; int y; public pairrr(int x, int y) { this.x = x; this.y = y; } public String toString() { return x + " " + y; } public boolean equals(Object o) { if (o instanceof pair) { pairrr p = (pairrr) o; return p.x == x && p.y == y; } return false; } public int hashCode() { return new Integer(x).hashCode() * 31 + new Integer(y).hashCode(); } public int compareTo(pairrr other) { if (this.x == other.x) { return Long.compare(this.y, other.y); } return Long.compare(this.x, other.x); } } static class tuble implements Comparable<tuble> { int x; int y; int z; public tuble(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public String toString() { return x + " " + y + " " + z; } public int compareTo(tuble other) { if (this.x == other.x) { if (this.y == other.y) { return this.z - other.z; } return this.y - other.y; } else { return this.x - other.x; } } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
00f17674dc88865cfbe6786ee1c3202d
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.lang.reflect.Array; import java.util.*; import java.io.*; import java.math.*; public class Main implements Runnable { final static int mod = 1000000007; static FastReader sc; static PrintWriter out; static boolean test_case_input = true; static final int MAX = 1000000001; static final int MIN = -1000000001; public static void solution(int test_case) throws IOException { // code int n = sc.nextInt(); Long a[] = sc.longarr(n); Arrays.sort(a); long sum = 0; long ans = 0; for(int i = 0; i < n; i++) { long curr = (i) * a[i] - sum; ans -= curr; sum += a[i]; } ans += a[n - 1]; out.println(ans); } // log A base B public static int logint(int x, int base) { return (int) (Math.log(x) / Math.log(base)); } public static int logint(long x, long base) { return (int) (Math.log(x) / Math.log(base)); } public static int logint(double x, double base) { return (int) (Math.log(x) / Math.log(base)); } public static double logdouble(int x, int base) { return (Math.log(x) / Math.log(base)); } public static double logdouble(long x, long base) { return (Math.log(x) / Math.log(base)); } public static double logdouble(double x, double base) { return (Math.log(x) / Math.log(base)); } public static long loglong(int x, int base) { return (long) (Math.log(x) / Math.log(base)); } public static long loglong(long x, long base) { return (long) (Math.log(x) / Math.log(base)); } public static long loglong(double x, double base) { return (long) (Math.log(x) / Math.log(base)); } // Debug public static void debug(String msg, Object value) { File output = new File("output.txt"); if (!output.exists()) return; String type = value.getClass().getSimpleName(); if (type.equals("int[]")) out.println(msg + " => " + Arrays.toString((int[]) value)); else if (type.equals("double[]")) out.println(msg + " => " + Arrays.toString((double[]) value)); else if (type.equals("float[]")) out.println(msg + " => " + Arrays.toString((float[]) value)); else if (type.equals("long[]")) out.println(msg + " => " + Arrays.toString((long[]) value)); else if (type.equals("char[]")) out.println(msg + " => " + Arrays.toString((char[]) value)); else if (type.equals("String[]")) out.println(msg + " => " + Arrays.toString((String[]) value)); else if (type.equals("int[][]")) { out.println(msg + "=>"); for (int i[] : (int[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("double[][]")) { out.println(msg + "=>"); for (double i[] : (double[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("float[][]")) { out.println(msg + "=>"); for (float i[] : (float[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("long[][]")) { out.println(msg + "=>"); for (long i[] : (long[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("char[][]")) { out.println(msg + "=>"); for (char i[] : (char[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("String[][]")) { out.println(msg + "=>"); for (String i[] : (String[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else out.println(msg + " => " + value); } public static void debug(Object value) { File output = new File("output.txt"); if (!output.exists()) return; String type = value.getClass().getSimpleName(); if (type.equals("int[]")) out.println(" => " + Arrays.toString((int[]) value)); else if (type.equals("double[]")) out.println(" => " + Arrays.toString((double[]) value)); else if (type.equals("float[]")) out.println(" => " + Arrays.toString((float[]) value)); else if (type.equals("long[]")) out.println(" => " + Arrays.toString((long[]) value)); else if (type.equals("char[]")) out.println(" => " + Arrays.toString((char[]) value)); else if (type.equals("String[]")) out.println(" => " + Arrays.toString((String[]) value)); else if (type.equals("int[][]")) { out.println("=>"); for (int i[] : (int[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("double[][]")) { out.println("=>"); for (double i[] : (double[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("float[][]")) { out.println("=>"); for (float i[] : (float[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("long[][]")) { out.println("=>"); for (long i[] : (long[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("char[][]")) { out.println("=>"); for (char i[] : (char[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else if (type.equals("String[][]")) { out.println("=>"); for (String i[] : (String[][]) value) out.println(" . " + Arrays.toString(i).replace(' ', '\t')); } else out.println(" => " + value); } // Graph Functions public static void addUndirectedEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) { adj.get(u).add(v); adj.get(v).add(u); } public static void addDirectedEdge(ArrayList<ArrayList<Integer>> adj, int u, int v) { adj.get(u).add(v); } public static <T> void addUndirectedEdge(ArrayList<ArrayList<Point>> adj, int u, int v, T weight) { adj.get(u).add(new Point(v, weight)); adj.get(v).add(new Point(u, weight)); } public static <T> void addDirectedEdge(ArrayList<ArrayList<Point>> adj, int u, int v, T weight) { adj.get(u).add(new Point(v, weight)); } public static <T> void toString(String msg, ArrayList<ArrayList<T>> adj) { out.println(msg + ":"); int count = 0; for (ArrayList<T> i : adj) { out.print("\t" + count++ + ": "); for (T j : i) { out.print(j + " "); } out.println(); } } public static void addUndirectedEdge(Map<Integer, ArrayList<Integer>> adj, int u, int v) { if (adj.containsKey(u)) { ArrayList<Integer> temp = adj.get(u); temp.add(v); adj.put(u, temp); } else { ArrayList<Integer> temp = new ArrayList<>(); temp.add(v); adj.put(u, temp); } if (adj.containsKey(v)) { ArrayList<Integer> temp = adj.get(v); temp.add(u); adj.put(v, temp); } else { ArrayList<Integer> temp = new ArrayList<>(); temp.add(u); adj.put(v, temp); } } public static void addDirectedEdge(Map<Integer, ArrayList<Integer>> adj, int u, int v) { if (adj.containsKey(u)) { ArrayList<Integer> temp = adj.get(u); temp.add(v); adj.put(u, temp); } else { ArrayList<Integer> temp = new ArrayList<>(); temp.add(v); adj.put(u, temp); } } public static <T> void addUndirectedEdge(Map<Integer, ArrayList<Point>> adj, int u, int v, T weight) { if (adj.containsKey(u)) { ArrayList<Point> temp = adj.get(u); temp.add(new Point(v, weight)); adj.put(u, temp); } else { ArrayList<Point> temp = new ArrayList<>(); temp.add(new Point(v, weight)); adj.put(u, temp); } if (adj.containsKey(v)) { ArrayList<Point> temp = adj.get(v); temp.add(new Point(u, weight)); adj.put(v, temp); } else { ArrayList<Point> temp = new ArrayList<>(); temp.add(new Point(u, weight)); adj.put(v, temp); } } public static <T> void addDirectedEdge(Map<Integer, ArrayList<Point>> adj, int u, int v, T weight) { if (adj.containsKey(u)) { ArrayList<Point> temp = adj.get(u); temp.add(new Point(v, weight)); adj.put(u, temp); } else { ArrayList<Point> temp = new ArrayList<>(); temp.add(new Point(v, weight)); adj.put(u, temp); } } public static <T> void toString(String msg, Map<T, ArrayList<T>> adj) { out.println(msg + ":"); for (Map.Entry<T, ArrayList<T>> entry : adj.entrySet()) { out.println("\t" + entry.getKey() + ": " + entry.getValue()); } } // GCD public static int __gcd(int a, int b) { BigInteger n1 = BigInteger.valueOf(a); BigInteger n2 = BigInteger.valueOf(b); BigInteger gcd = n1.gcd(n2); return gcd.intValue(); } public static long __gcd(long a, long b) { BigInteger n1 = BigInteger.valueOf(a); BigInteger n2 = BigInteger.valueOf(b); BigInteger gcd = n1.gcd(n2); return gcd.longValue(); } public static void main(String args[]) throws IOException { new Thread(null, new Main(), "random", 1 << 26).start(); } @Override public void run() { long start = 0, end = 0; try { File output = new File("output.txt"); sc = new FastReader(); if (output.exists()) { out = new PrintWriter(new FileOutputStream("output.txt")); start = System.nanoTime(); } else { out = new PrintWriter(System.out); } int test_cases = 1; if (test_case_input) test_cases = sc.nextInt(); for (int i = 1; i <= test_cases; i++) { solution(i); } if (output.exists()) { end = System.nanoTime(); out.println("Execution time: " + (end - start) / 1000000 + " ms"); } out.flush(); out.close(); } catch (Exception e) { out.println("Exception: " + e); out.println("At Line no. : " + e.getStackTrace()[0].getLineNumber()); out.flush(); out.close(); return; } } // Edge Class static class Edge implements Comparable<Edge> { Object u; Object v; Object wt; public Edge(Object origin, Object destination, Object weight) { u = origin; v = destination; wt = weight; } public String toString() { String ans = u + " -> " + v + " : " + wt; return ans; } public int getIntOrigin() { return (int) u; } public int getIntDestination() { return (int) v; } public int getIntWeight() { return (int) wt; } public long getLongOrigin() { return (long) u; } public long getLongDestination() { return (long) v; } public long getLongWeight() { return (long) wt; } @Override public int compareTo(Edge edge) { if ((edge.u).getClass() == Long.class) return (((Long) this.wt).compareTo((Long) edge.wt)); else return (((Integer) this.wt).compareTo((Integer) edge.wt)); } } // Point Class static class Point implements Comparable<Point> { Object x; Object y; public Point(Object a, Object b) { x = a; y = b; } public int getIntX() { return (int) x; } public int getIntY() { return (int) y; } public long getLongX() { return (long) x; } public long getLongY() { return (long) y; } public int compareTo(Point obj) { if (obj.x.equals(this.x)) { if ((obj.y).getClass() == Long.class) return ((Long) this.y).compareTo((Long) obj.y); else return ((Integer) this.y).compareTo((Integer) obj.y); } else { if ((obj.x).getClass() == Long.class) return ((Long) this.x).compareTo((Long) obj.x); else return ((Integer) this.x).compareTo((Integer) obj.x); } } public String toString() { String ans = "(" + x + ", " + y + ")"; return ans; } @Override public int hashCode() { int hash = 7; hash = 71 * hash + (int) this.x; hash = 71 * hash + (int) this.y; return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; Point point = (Point) obj; if (point.x.equals(this.x) && point.y.equals(this.y)) return true; else return false; } } // Fast IO static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() throws FileNotFoundException { File in = new File("input.txt"); if (in.exists()) { br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); } else { 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()); } float nextFloat() { return Float.parseFloat(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } Integer[] intarr(int n) { Integer a[] = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(next()); } return a; } Long[] longarr(int n) { Long a[] = new Long[n]; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(next()); } return a; } float[] floatarr(int n) { float a[] = new float[n]; for (int i = 0; i < n; i++) { a[i] = Float.parseFloat(next()); } return a; } Double[] doublearr(int n) { Double a[] = new Double[n]; for (int i = 0; i < n; i++) { a[i] = Double.parseDouble(next()); } return a; } Integer[][] intmatrix(int row, int col) { Integer a[][] = new Integer[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Integer.parseInt(next()); } } return a; } Long[][] longmatrix(int row, int col) { Long a[][] = new Long[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Long.parseLong(next()); } } return a; } Float[][] floatmatrix(int row, int col) { Float a[][] = new Float[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Float.parseFloat(next()); } } return a; } Double[][] doublematrix(int row, int col) { Double a[][] = new Double[row][col]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { a[i][j] = Double.parseDouble(next()); } } return a; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
64d1284f2b40801221cd70bc87ba7930
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader fs = new FastReader(); int t = fs.nextInt(); StringBuilder sb = new StringBuilder(); while(t-- > 0){ int n = fs.nextInt(); List<Long> l = new ArrayList<>(); for(int i=0;i<n;i++) l.add(fs.nextLong()); Collections.sort(l); long[] pre = new long[n]; long to = 0; long sum = 0; for(int i=1;i<n;i++){ long dif = l.get(i) - l.get(i-1); to+=dif; long req = dif*i; pre[i] = pre[i-1]+req; sum+=pre[i]; } // System.out.println(to+" "+sum); sb.append(to-sum).append("\n"); } System.out.println(sb); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
6a34b8bd8e802af527d1b59681cacaf1
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.awt.dnd.DragSource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; public class CSES { static int one(int n){ int ans=0; while(n>0){ ans++; n = n&(n-1); } return ans; } public static void main(String[] args) throws IOException { FastScanner s = new FastScanner(); int t = s.nextInt(); // int t=1; while (t-- > 0) { int n = s.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = s.nextLong(); } sort(a); long ans = a[n-1]; long[] ne = new long[n]; ne[0] = 0; for(int i=1;i<n;i++){ ne[i] = ne[i-1] + i*(a[i]-a[i-1]); ans-=ne[i]; } System.out.println(ans); } } static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static void sortr(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l,Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
1dba41b6cfc351553c9865359b632204
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.awt.dnd.DragSource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; public class CSES { static int one(int n){ int ans=0; while(n>0){ ans++; n = n&(n-1); } return ans; } public static void main(String[] args) throws IOException { FastScanner s = new FastScanner(); int t = s.nextInt(); // int t=1; while (t-- > 0) { int n = s.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = s.nextLong(); } sort(a); long cnt=0,ans=0; for(int i=2;i<n;i++){ cnt+=a[i-2]; ans-=(a[i]*(long)(i-1)); ans+=cnt; } System.out.println(ans); } } static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);} static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);} static void sortr(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l,Collections.reverseOrder()); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
90186b6808ef7bed253024ae73d7bffa
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C_Great_Graphs { static Scanner in=new Scanner(); static PrintWriter out=new PrintWriter( System.out ); static int testCases,n; static long a[]; static void merge(long a[],int left,int right,int mid){ int n1=mid-left+1,n2=right-mid; long L[]=new long[n1]; long R[]=new long[n2]; for(int i=0;i<n1;i++){ L[i]=a[left+i]; } for(int i=0;i<n2;i++){ R[i]=a[mid+1+i]; } int i=0,j=0,k=left; while(i<n1 && j<n2){ if(L[i]<=R[j]){ a[k]=L[i]; i++; }else{ a[k]=R[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=R[j]; j++; k++; } } static void sort(long a[],int left,int right){ if(left>=right){ return; } int mid=(left+right)/2; sort(a,left,mid); sort(a,mid+1,right); merge(a,left,right,mid); } static void solve(){ sort(a,0,n-1); long pre[]=new long[n]; pre[0]=a[0]; for(int i=1;i<n;i++){ pre[i]=pre[i-1]+a[i]; } /* for(int i=0;i<n;i++){ out.print(pre[i]+" "); out.flush(); } out.println(); out.flush();*/ long value=0,sum=0; for(int i=2;i<n;i++){ //sum+=a[i-2]; value-=(a[i]*(i-1)); value+=pre[i-2]; } out.println(value); out.flush(); } public static void main(String[] amit) throws IOException { testCases=in.nextInt(); for(int t=0;t<testCases;t++){ n=in.nextInt(); a=new long[n]; for(int i=0;i<n;i++){ a[i]=in.nextLong(); } solve(); } } static class Scanner{ BufferedReader in; StringTokenizer st; public Scanner() { in=new BufferedReader( new InputStreamReader( System.in ) ); } String next() throws IOException{ while( st==null || !st.hasMoreElements() ){ st=new StringTokenizer(in.readLine()); } return st.nextToken(); } String nextLine() throws IOException{ return in.readLine(); } int nextInt() throws IOException{ return Integer.parseInt( next() ); } long nextLong() throws IOException{ return Long.parseLong( next() ); } } } /* 3 3 0 2 3 2 0 1000000000 1 0 */ /* 1 5 3 1 5 9 2 */
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
05f3fcfec08936cde1355562dcbde8a1
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class C_Great_Graphs { static Scanner in=new Scanner(); static PrintWriter out=new PrintWriter( System.out ); static int testCases,n; static long a[]; static void merge(long a[],int left,int right,int mid){ int n1=mid-left+1,n2=right-mid; long L[]=new long[n1]; long R[]=new long[n2]; for(int i=0;i<n1;i++){ L[i]=a[left+i]; } for(int i=0;i<n2;i++){ R[i]=a[mid+1+i]; } int i=0,j=0,k=left; while(i<n1 && j<n2){ if(L[i]<=R[j]){ a[k]=L[i]; i++; }else{ a[k]=R[j]; j++; } k++; } while(i<n1){ a[k]=L[i]; i++; k++; } while(j<n2){ a[k]=R[j]; j++; k++; } } static void sort(long a[],int left,int right){ if(left>=right){ return; } int mid=(left+right)/2; sort(a,left,mid); sort(a,mid+1,right); merge(a,left,right,mid); } static void solve(){ sort(a,0,n-1); long value=0,sum=0; for(int i=2;i<n;i++){ sum+=a[i-2]; value-=(a[i]*(i-1)); value+=sum; } out.println(value); out.flush(); } public static void main(String[] amit) throws IOException { testCases=in.nextInt(); for(int t=0;t<testCases;t++){ n=in.nextInt(); a=new long[n]; for(int i=0;i<n;i++){ a[i]=in.nextLong(); } solve(); } } static class Scanner{ BufferedReader in; StringTokenizer st; public Scanner() { in=new BufferedReader( new InputStreamReader( System.in ) ); } String next() throws IOException{ while( st==null || !st.hasMoreElements() ){ st=new StringTokenizer(in.readLine()); } return st.nextToken(); } String nextLine() throws IOException{ return in.readLine(); } int nextInt() throws IOException{ return Integer.parseInt( next() ); } long nextLong() throws IOException{ return Long.parseLong( next() ); } } } /* 3 3 0 2 3 2 0 1000000000 1 0 */
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
ac2c978e946fbf6c0cfe7f2584ea2921
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class GreatGraphs { public static void solution() { //TODO } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int tt = Integer.parseInt(reader.readLine()); // One number per line for (int t = 0; t < tt; t++) { int length = Integer.parseInt(reader.readLine()); StringTokenizer info = new StringTokenizer(reader.readLine()); // Multiple numbers per line long[] arr = new long[length]; for (int i = 0; i < length; i++) { arr[i] = Integer.parseInt(info.nextToken()); // For next number } Arrays.sort(arr); long sum = 0; long ans = 0; for (int i = 1; i < length; i++) { sum += i * (arr[i] - arr[i - 1]); ans += sum; } writer.println(arr[length - 1] - ans); } reader.close(); writer.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
fdd3f136b0d705d37661d262105aa637
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.lang.*; import java.math.BigInteger; import java.util.Scanner; import java.io.*; import java.util.*; import javafx.util.Pair; import java.math.*; import java.awt.Point; public class Main { static FastScanner sc = new FastScanner(); static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static void print(int[] arr){ for(int i = 0; i < arr.length; i++){ System.out.print(arr[i] + " "); } System.out.println(); } static void solve(){ int n = sc.ni(); long[] arr = new long[n]; for(int i = 0; i < n; i++){ arr[i] = sc.ni(); } sort(arr); long pref[] = new long[n]; pref[0] = arr[0]; for(int i = 1; i < n; i++){ pref[i] = pref[i - 1] + (arr[i] - arr[i - 1]); } long suf[] = new long[n]; suf[n - 1] = pref[n - 1]; for(int i = n - 2; i >= 0; i--){ suf[i] = pref[i] + suf[i + 1]; } long ans = 0; for(int i = 1; i < n - 1; i++){ ans -= (n - i - 1) * pref[i - 1]; ans += suf[i + 1]; } System.out.println(-ans); } public static void main(String[] args) { int t = sc.ni(); for(int i = 0; i < t; i++){ solve(); } } } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in), 32768); st = null; } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int ni() { return Integer.parseInt(next()); } long nl() { return Long.parseLong(next()); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
2e2884ef8a9031632b9964c8f0812d22
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int readInt() throws IOException { return Integer.parseInt(next()); } static long readLong() throws IOException { return Long.parseLong(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readChar() throws IOException { return next().charAt(0); } static String readLine() throws IOException { return br.readLine(); } static class Pair implements Comparable<Pair> { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } public int compareTo(Pair other) { if (this.f != other.f) return this.f - other.f; return this.s - other.s; } } public static void main(String[] args) throws IOException { for (int t = readInt(); t > 0; --t) { int n = readInt(); long d[] = new long[n + 1]; for (int i = 1; i <= n; ++i) d[i] = readInt(); Arrays.sort(d, 1, n + 1); long ans = 0, sum = d[1]; for (int i = 2; i <= n; ++i) { if (d[i] > 0) ans += d[i] - d[i - 1]; ans += sum - d[i]*(i - 1); sum += d[i]; } System.out.println(ans); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
9c16dc890be6395ce06dbfdd600f8e8e
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int readInt() throws IOException { return Integer.parseInt(next()); } static long readLong() throws IOException { return Long.parseLong(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readChar() throws IOException { return next().charAt(0); } static String readLine() throws IOException { return br.readLine(); } static class Pair implements Comparable<Pair> { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } public int compareTo(Pair other) { if (this.f != other.f) return this.f - other.f; return this.s - other.s; } } public static void main(String[] args) throws IOException { for (int t = readInt(); t > 0; --t) { int n = readInt(); long d[] = new long[n + 1]; for (int i = 1; i <= n; ++i) d[i] = readInt(); if (n == 1) { System.out.println(0); continue; } Arrays.sort(d, 1, n + 1); long ans = 0, sum = d[1]; for (int i = 2; i <= n; ++i) { if (d[i] > 0) ans += d[i] - d[i - 1]; ans += sum - d[i]*(i - 1); sum += d[i]; } System.out.println(ans); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
0574a4f90fd8c106747b29d3bb8f60ae
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; //https://codeforces.com/contest/1541/problem/C public class GreatGraph { public static void main(String [] args) { Scanner myObj = new Scanner(System.in); // Create a Scanner object int t = myObj.nextInt(); while(t!=0) { int n = myObj.nextInt(); List<Integer> input = new ArrayList<>(); for(int i=0;i<n;i++) { int val = myObj.nextInt(); input.add(val); } Collections.sort(input); long sum = 0; int prev = input.get(0); for(int i=1;i<n;i++) { sum += (input.get(i) - prev); prev = input.get(i); } long count = 1; long prefixSum = 0; long negativeSum = 0; for(int i=1;i<n;i++) { long val = count * input.get(i) - prefixSum; negativeSum += val; prefixSum += input.get(i); count++; } negativeSum = negativeSum * -1; long ans = sum + negativeSum; System.out.println(ans); t--; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
c0c0668d9e19ec09757295e0eac141b2
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { /************************ SOLUTION STARTS HERE ************************/ public static boolean IsPowerOfTwo(int x) { return (x & (x - 1)) == 0; } // function to check if // point collinear or not static boolean collinear(double x1, double y1, double x2, double y2, double x3, double y3) { double a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); return a==0d; } static double area(double x1, double y1, double x2, double y2, double x3, double y3) { double a = x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2); return a; } public static class Node implements Comparable<Node>{ long v; long i; Node(long v, long i) { this.v = v; this.i = i; } @Override public int compareTo(Node o) { return (int)(this.v - o.v); } } private static void solve() { int t = nextInt(); while(t-- > 0) { int n = nextInt(); long[] arr = nextLongArray(n); Arrays.sort(arr); // long tsum = 0; // for(int i=n-1;i>0;i--) { // long curSum = 0; // for(int j=i-2;j>=0; j--) { // curSum += (arr[i] - arr[j]); // } // tsum+= (-1*curSum); // } // println(tsum); long[] sum = new long[n]; for(int i=1;i<n;i++) { sum[i] = arr[i] + sum[i-1]; } // long tsum1 = 0; for(int i=2;i<n;i++) { tsum1 += (arr[i]*(i-1) - sum[i-2]); } // println(-1*tsum1); } } /************************ SOLUTION ENDS HERE ************************/ /************************ TEMPLATE STARTS HERE **********************/ public static void main(String[] args) throws IOException { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false); st = null; solve(); reader.close(); writer.close(); } static BufferedReader reader; static PrintWriter writer; static StringTokenizer st; static String next() { while (st == null || !st.hasMoreTokens()) { try { String line = reader.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } static String nextLine() { String s = null; try { s = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return s; } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble() { return Double.parseDouble(next()); } static char nextChar() { return next().charAt(0); } static int[] nextIntArray(int n) { int[] a = new int[n]; int i = 0; while (i < n) { a[i++] = nextInt(); } return a; } static long[] nextLongArray(int n) { long[] a = new long[n]; int i = 0; while (i < n) { a[i++] = nextLong(); } return a; } static int[] nextIntArrayOneBased(int n) { int[] a = new int[n + 1]; int i = 1; while (i <= n) { a[i++] = nextInt(); } return a; } static long[] nextLongArrayOneBased(int n) { long[] a = new long[n + 1]; int i = 1; while (i <= n) { a[i++] = nextLong(); } return a; } static void print(Object o) { writer.print(o); } static void println(Object o) { writer.println(o); } static void printArr(int[] arr) { for(int i = 0 ; i < arr.length; i++) System.out.print(arr[i] + " "); System.out.println(); } /************************ TEMPLATE ENDS HERE ************************/ }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
7cc272e69563aefd08b55bdbed5714f4
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; public class First { 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(); //int a = 1; int t; t = in.nextInt(); //t = 1; while (t > 0) { //out.print("Case #"+(a++)+": "); solver.call(in, out); t--; } out.close(); } static class TaskA { public void call(InputReader in, PrintWriter out) { int n; n = in.nextInt(); long[] arr = new long[n+1]; long ans = 0; long a = 0; for (int i = 1; i <= n; i++) { arr[i] = in.nextLong(); } sort(arr); for (int i = 1; i <= n; i++) { arr[i] -= a; a+=arr[i]; ans +=arr[i]; } long b = 0, c = 0; long j = 0; for (int i = n; i > 1; i--) { b += (i-1); c += j; ans -= (b-c) *arr[i]; j++; } out.println(ans); } } static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static class answerl implements Comparable<answerl>{ long a; long b; public answerl(long a, long b) { this.a = a; this.b = b; } @Override public int compareTo(answerl o) { return Long.compare(this.b, o.b); } } static class answer implements Comparable<answer>{ int a; int b; public answer(int a, int b) { this.a = a; this.b = b; } @Override public int compareTo(answer o) { return this.a - o.a; } } static class answer1 implements Comparable<answer1>{ int a, b, c; public answer1(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } @Override public int compareTo(answer1 o) { return this.a - o.a; } } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static void sort(long[] a) { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static final Random random=new Random(); static void shuffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong(){ return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
f6d1349f0ee985aa171f86c3d01f3b3e
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class codeforces { static int M = 1_000_000_007; static int INF = 2_000_000_000; static final FastScanner fs = new FastScanner(); //variable public static void main(String[] args) throws IOException { int T = fs.nextInt(); while(T-->0) { int n = fs.nextInt(); int[] arr = fs.arrayIn(n); ruffleSort(arr); if(n<3) System.out.println(0); else { long sum = 0; long[] pre = new long[n+1]; for(int i=1;i<n;i++) pre[i] = pre[i-1] + arr[i-1]; for(int i=2;i<n;i++) { sum -= (long) (i-1) *(arr[i]); sum += pre[i-1]; } System.out.println(sum); } } } //class //function // Template static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } static int gcd(int a, int b) { if(a==0) return b; return gcd(b%a,a); } static void premutation(int n, ArrayList<Integer> arr,boolean[] chosen) { if(arr.size() == n) { }else { for(int i=1; i<=n; i++) { if(chosen[i]) continue; arr.add(i); chosen[i] = true; premutation(n,arr,chosen); arr.remove(i); chosen[i] = false; } } } static boolean isPalindrome(char[] c) { int n = c.length; for(int i=0; i<n/2; i++) { if(c[i] != c[n-i-1]) return false; } return true; } static long nCk(int n, int k) { return (modMult(fact(n),fastexp(modMult(fact(n-k),fact(k)),M-2))); } static long fact (long n) { long fact =1; for(int i=1; i<=n; i++) { fact = modMult(fact,i); } return fact%M; } static int modMult(long a,long b) { return (int) (a*b%M); } static int negMult(long a,long b) { return (int)((a*b)%M + M)%M; } static long fastexp(long x, int y){ if(y==1) return x; long ans = fastexp(x,y/2); if(y%2 == 0) return modMult(ans,ans); else return modMult(ans,modMult(ans,x)); } static final Random random = new Random(); static void ruffleSort(int[] arr) { int n = arr.length; for(int i=0; i<n; i++) { int j = random.nextInt(n); int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } public static class Pairs implements Comparable<Pairs> { long f,s; Pairs(long f, long s) { this.f = f; this.s = s; } public int compareTo(Pairs p) { return Long.compare(this.f,p.f); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Pairs)) return false; Pairs pairs = (Pairs) o; return f == pairs.f && s == pairs.s; } @Override public int hashCode() { return Objects.hash(f, s); } } } class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer str = new StringTokenizer(""); String next() throws IOException { while(!str.hasMoreTokens()) str = new StringTokenizer(br.readLine()); return str.nextToken(); } char nextChar() throws IOException { return next().charAt(0); } int nextInt() throws IOException { return Integer.parseInt(next()); } float nextFloat() throws IOException { return Float.parseFloat(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } byte nextByte() throws IOException { return Byte.parseByte(next()); } int [] arrayIn(int n) throws IOException { int[] arr = new int[n]; for(int i=0; i<n; i++) { arr[i] = nextInt(); } return arr; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
3a922c4bda21f3c5a84c23bf2ca1b5f5
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String args[]) { FastReader input=new FastReader(); PrintWriter out=new PrintWriter(System.out); int T=input.nextInt(); while(T-->0) { int n=input.nextInt(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0;i<n;i++) { int d=input.nextInt(); list.add(d); } if(n<=2) { out.println(0); } else { long sum=0; Collections.sort(list); long pre=0; for(int i=list.size()-1;i>0;i--) { pre+=list.get(i); sum+=pre; } pre=0; for(int i=0;i<list.size()-1;i++) { pre+=list.get(i); sum-=pre; } out.println(list.get(list.size()-1)-sum); } } out.close(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
8dd0b4a2cecf7b12b53c17f4fd250c2d
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.util.stream.Collectors; import java.io.*; import java.math.*; public class R775_C{ public static FastScanner sc; public static PrintWriter pw; public static StringBuilder sb; public static int MOD= 1000000007; public static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void printList(List<Long> al) { System.out.println(al.stream().map(it -> it.toString()).collect(Collectors.joining(" "))); } public static void printList(Deque<Long> al) { System.out.println(al.stream().map(it -> it.toString()).collect(Collectors.joining(" "))); } public static void printArr(long[] arr) { System.out.println(Arrays.toString(arr).trim().replace("[", "").replace("]","").replace(","," ")); } public static long gcd(long a, long b) { if(b==0) return a; return gcd(b,a%b); } public static long lcm(long a, long b) { return((a*b)/gcd(a,b)); } public static void decreasingOrder(ArrayList<Long> al) { Comparator<Long> c = Collections.reverseOrder(); Collections.sort(al,c); } public static boolean[] sieveOfEratosthenes(int n) { boolean isPrime[] = new boolean[n+1]; Arrays.fill(isPrime, true); isPrime[0]=false; isPrime[1]=false; for(int i=2;i*i<n;i++) { for(int j=2*i;j<n;j+=i) { isPrime[j]=false; } } return isPrime; } public static long nCr(long N, long R) { double result=1; for(int i=1;i<=R;i++) result=((result*(N-R+i))/i); return (long) result; } public static long fastPow(long a, long b, int n) { long result=1; while(b>0) { if((b&1)==1) result=(result*a %n)%n; a=(a%n * a%n)%n; b>>=1; } return result; } public static int BinarySearch(long[] arr, long key) { int low=0; int high=arr.length-1; while(low<=high) { int mid=(low+high)/2; if(arr[mid]==key) return mid; else if(arr[mid]>key) high=mid-1; else low=mid+1; } return low; //High=low-1 } public static void solve(int t) { int n=sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++) arr[i]=sc.nextInt(); Arrays.sort(arr); long[] prefixSum= new long[n]; prefixSum[0]=arr[0]; for(int i=1;i<n;i++) { prefixSum[i]=prefixSum[i-1]+(long)arr[i]; } long ans=arr[n-1]; for(int i=1;i<n;i++) { ans-=(long)arr[i]*(long)i-prefixSum[i-1]; } System.out.println(ans); } public static void main(String[] args) { sc = new FastScanner(); pw = new PrintWriter(new OutputStreamWriter(System.out)); sb= new StringBuilder(""); int t=sc.nextInt(); for(int i=1;i<=t;i++) solve(i); System.out.println(sb); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
479bba97ba28604d7af407274007ccce
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; // for codechef and atcoder and spoj public class Main { BufferedReader br; StringTokenizer st; public Main() { // constructor br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong () { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } static void sort(int[] arr) { int n = arr.length; Random rnd = new Random(); for(int i = 0; i < n; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static void sort(long[] arr) { int n = arr.length; Random rnd = new Random(); for(int i = 0; i < n; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(n - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } Arrays.sort(arr); } static long gcd(long a, long b) { if(b == 0) { return a; } return gcd(b, a % b); } static int dir[][] = {{1, 0}, {-1, 0}, {0 ,1}, {0, -1}}; static long mod = 998244353; public static void main(String[] args) throws Exception{ Main in = new Main(); PrintWriter out = new PrintWriter(System.out); int test = in.nextInt(); while(test-- > 0) { int n = in.nextInt(); int arr[] = new int[n]; for(int i = 0; i < n; i++) { arr[i] = in.nextInt(); } sort(arr); long sum = 0; long psum[] = new long[n]; for(int i = 0; i < n; i++) { sum += arr[i]; psum[i] = sum; } long ans = 0; for(int i = 1; i < n; i++) { ans = ans + (arr[i] * 1L * (i) - psum[i - 1]); } long k = 0; for(int i = 1; i < n; i++) { k += arr[i] - arr[i - 1]; } out.println(k - ans); } out.flush(); out.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
ed368cf033cf7ca1917e04ab721eb2bf
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; // cd C:\Users\Lenovo\Desktop\New //ArrayList<Integer> a=new ArrayList<>(); //List<Integer> lis=new ArrayList<>(); //StringBuilder ans = new StringBuilder(); //HashMap<Integer,Integer> map=new HashMap<>(); public class cf { static FastReader in=new FastReader(); static final Random random=new Random(); static long mod=1000000007L; public static void main(String args[]) throws IOException { FastReader sc=new FastReader(); //Scanner s=new Scanner(System.in); int tt=sc.nextInt(); //int tt=1; while(tt-->0){ //StringBuilder ar = new StringBuilder(); int n = sc.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextInt(); } ruffleSort(arr); long answer = 0; long runninSum = arr[0]; for (int i = 1; i < n; i++) { answer += arr[i] - arr[i - 1]; answer -= (1l*arr[i] * i - runninSum); runninSum += arr[i]; } System.out.println(answer); } } static int count(int arr[],int idx,long sum,int []dp){ if(idx>=arr.length){ return 0; } if(dp[idx]!=-1){ return dp[idx]; } if(arr[idx]<0){ return dp[idx]=Math.max(1+count(arr,idx+1,sum+arr[idx],dp),count(arr,idx+1,sum,dp)); } else{ return dp[idx]=1+count(arr,idx+1,sum+arr[idx],dp); } } static String reverse(String s){ String ans=""; for(int i=s.length()-1;i>=0;i--){ ans+=s.charAt(i); } return ans; } static int find_max(int []check,int y){ int max=0; for(int i=y;i>=0;i--){ if(check[i]!=0){ max=i; break; } } return max; } static void dfs(int [][]arr,int row,int col,boolean [][]seen,int n){ if(row<0 || col<0 || row==n || col==n){ return; } if(arr[row][col]==1){ return; } if(seen[row][col]==true){ return; } seen[row][col]=true; dfs(arr,row+1,col,seen,n); dfs(arr,row,col+1,seen,n); dfs(arr,row-1,col,seen,n); dfs(arr,row,col-1,seen,n); } static int msb(int x){ int ans=0; while(x!=0){ x=x/2; ans++; } return ans; } static void ruffleSort(int[] a) { int n=a.length; for (int i=0; i<n; i++) { int oi=random.nextInt(n), temp=a[oi]; a[oi]=a[i]; a[i]=temp; } Arrays.sort(a); } static int gcd(int a,int b) { if(b==0) { return a; } return gcd(b,a%b); } /* static boolean checkprime(int n1) { if(n1%2==0||n1%3==0) return false; else { for(int i=5;i*i<=n1;i+=6) { if(n1%i==0||n1%(i+2)==0) return false; } return true; } } */ /* Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator(); while(iterator.hasNext()){ Map.Entry<Integer, Integer> entry = iterator.next(); int value = entry.getValue(); if(value==1){ iterator.remove(); } else{ entry.setValue(value-1); } } */ static class Pair implements Comparable { int a,b; public String toString() { return a+" " + b; } public Pair(int x , int y) { a=x;b=y; } @Override public int compareTo(Object o) { Pair p = (Pair)o; if(p.a!=a){ return a-p.a;//in } else{ return b-p.b;// } } } /* public static boolean checkAP(List<Integer> lis){ for(int i=1;i<lis.size()-1;i++){ if(2*lis.get(i)!=lis.get(i-1)+lis.get(i+1)){ return false; } } return true; } public static int minBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]>=val){ r=mid; } else{ l=mid; } } return r; } public static int maxBS(int[]arr,int val){ int l=-1; int r=arr.length; while(r>l+1){ int mid=(l+r)/2; if(arr[mid]<=val){ l=mid; } else{ r=mid; } } return l; } static int lcm(int a, int b) { return (a / gcd(a, b)) * b; }*/ static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
044984cc31c7532086ce49e498e8ab60
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class C { public static void main(String[] args) { FastReader f = new FastReader(); StringBuffer sb=new StringBuffer(); int test=f.nextInt(); out: while(test-->0) { int n=f.nextInt(); int d[]=new int[n]; for(int i=0;i<n;i++) d[i]=f.nextInt(); Arrays.sort(d); long pre[]=new long[n]; pre[0]=d[0]; for(int i=1;i<n;i++) pre[i]=pre[i-1]+d[i]; long ans=0; for(int i=2;i<n;i++) { long var=(long)(i-1)*d[i] - pre[i-2]; ans+=var; } sb.append(-ans+"\n"); } System.out.println(sb); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try{ st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
6706b6c3b4ca7f33274a0d24808a8393
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import javafx.scene.layout.Priority; import sun.reflect.generics.tree.Tree; import java.awt.*; import java.sql.Array; import java.util.*; import java.io.*; import java.util.stream.Stream; import static java.lang.Math.*; public class C { static InputReader in=new InputReader(System.in); static OutputWriter out=new OutputWriter(System.out); static StringBuilder sb=new StringBuilder(); static long MOD = (long)(998244353); // Main Class Starts Here public static void main(String args[])throws IOException { // Write your code. int t = in(); while(t-->0) { int n = in(); long a[] = lan(n); if(n < 3){ app(0+"\n"); } else{ Arrays.sort(a); long sum = 0L; for(int i = 0; i < n; i++){ sum += a[i] * i + (-1 * a[i] * (n-1-i)); } sum -= a[n-1]; sum = -1L*sum; app(sum+"\n"); } } out.printLine(sb); out.close(); } static class Pair{ int index; int height; public Pair(int index, int height){ this.index = index; this.height = height; } public String toString(){ return "[ "+index+" , "+height+" ]"; } } static class DisjointSet{ int par[]; int rank[]; int n; public DisjointSet(int n){ this.n = n; par = new int[n]; rank = new int[n]; for(int i = 0; i < n; i++){ par[i] = i; } } public int findPar(int i){ // path compression. if(par[i] != i){ par[i] = findPar(par[i]); } return par[i]; } public int merge(int x, int y){ int parX = findPar(x); int parY = findPar(y); if(parX == parY) return 0; // no decrease in connected components if(rank[parX] > rank[parY]){ // merge y to x. par[parY] = parX; } else if(rank[parY] > rank[parX]){ par[parX] = parY; } else{ par[parY] = parX; rank[parX]++; } return 1; // after merging the decrease in connected components is 1. } } public static class Edge{ int from; int to; int id; boolean visited; public Edge(int from, int to, int id){ this.from = from; this.to = to; this.id =id; this.visited = false; } } public static int[] an(int n) { int ar[]=new int[n]; for(int i=0;i<n;i++) ar[i]=in(); return ar; } public static long[] lan(int n) { long ar[]=new long[n]; for(int i=0;i<n;i++) ar[i]=lin(); return ar; } public static String atos(Object ar[]) { return Arrays.toString(ar); } public static int in() { return in.readInt(); } public static long lin() { return in.readLong(); } public static String sn() { return in.readString(); } public static void prln(Object o) { out.printLine(o); } public static void prn(Object o) { out.print(o); } public static void display(int a[]) { out.printLine(Arrays.toString(a)); } public static HashMap<Integer,Integer> hm(int a[]){ HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0; i < a.length;i++) { int keep = (int)map.getOrDefault(a[i],0); map.put(a[i],++keep); } return map; } public static void app(Object o) { sb.append(o); } public static long calcManhattanDist(int x1,int y1,int x2,int y2) { long xa = Math.abs(x1-x2); long ya = Math.abs(y1-y2); return (xa+ya); } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
a37c387feb768583190007e1af0a4e4e
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class cf1541 { 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 t = in.nextInt(); while (t-- != 0) { int n = in.nextInt(); long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) { a[i] = in.nextLong(); } Arrays.sort(a, 1, n + 1); for(int i=n;i>1;i--) { a[i] = a[i]-a[i-1]; } long p = n-1; long cnt = p; long ans =0 ; for(int i=2,j=n;i<j;i++,j--) { ans -= (a[i]+a[j])*(p-1); cnt-=2; p+=cnt; } if((n&1)==0) { ans -= a[n/2+1]*(p-1); } out.println(ans); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreElements()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
38deb4784484b285434741421312b118
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class GreatGraphs { static int mod = 1000000007; public static void main(String[] args) throws IOException { FastReader reader = new FastReader(); FastWriter writer = new FastWriter(); int numTests = reader.readSingleInt(); for(int t = 0; t<numTests; t++){ int n = reader.readSingleInt(); int[] integers = reader.readIntArray(n); mergeSort(integers, n); long cost = 0; long diff = 0; for(int i = 1; i<n; i++){ diff = diff + (long)(integers[i]-integers[i-1])*(long)(i); cost = cost-diff; } cost += integers[n-1]; writer.writeSingleLong(cost); } } public static void mergeSort(int[] a, int n) { if (n < 2) { return; } int mid = n / 2; int[] l = new int[mid]; int[] r = new int[n - mid]; for (int i = 0; i < mid; i++) { l[i] = a[i]; } for (int i = mid; i < n; i++) { r[i - mid] = a[i]; } mergeSort(l, mid); mergeSort(r, n - mid); merge(a, l, r, mid, n - mid); } public static void merge(int[] a, int[] l, int[] r, int left, int right) { int i = 0, j = 0, k = 0; while (i < left && j < right) { if (l[i] <= r[j]) { a[k++] = l[i++]; } else { a[k++] = r[j++]; } } while (i < left) { a[k++] = l[i++]; } while (j < right) { a[k++] = r[j++]; } } public static class FastReader { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tokenizer; public int readSingleInt() throws IOException { return Integer.parseInt(reader.readLine()); } public int[] readIntArray(int numInts) throws IOException { int[] nums = new int[numInts]; tokenizer = new StringTokenizer(reader.readLine()); for(int i = 0; i<numInts; i++){ nums[i] = Integer.parseInt(tokenizer.nextToken()); } return nums; } public String readString() throws IOException { return reader.readLine(); } } public static class FastWriter { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out)); public void writeSingleInteger(int i) throws IOException { writer.write(Integer.toString(i)); writer.newLine(); writer.flush(); } public void writeSingleLong(long i) throws IOException { writer.write(Long.toString(i)); writer.newLine(); writer.flush(); } public void writeIntArrayWithSpaces(int[] nums) throws IOException { for(int i = 0; i<nums.length; i++){ writer.write(nums[i] + " "); } writer.newLine(); writer.flush(); } public void writeIntArrayWithoutSpaces(int[] nums) throws IOException { for(int i = 0; i<nums.length; i++){ writer.write(Integer.toString(nums[i])); } writer.newLine(); writer.flush(); } public void writeString(String s) throws IOException { writer.write(s); writer.newLine(); writer.flush(); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
6102d93b7d04f38c8cc150f5c2450d32
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/*========================================================================== * AUTHOR: RonWonWon * CREATED: 27.06.2021 22:50:11 /*==========================================================================*/ import java.io.*; import java.util.*; public class C { public static void main(String[] args) throws IOException { /* in.ini(); PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); */ long startTime = System.nanoTime(); int t = in.nextInt(), T = 1; while(t-->0) { int n = in.nextInt(); long d[] = in.readArrayL(n); ruffleSortL(d); long time = d[n-1]; long prefix[] = new long[n]; prefix[0] = d[0]; for(int i=1;i<n;i++) prefix[i] = prefix[i-1] + d[i]; for(int i=n-1;i>0;i--){ time -= (d[i]*i - prefix[i-1]); } out.println(time); //out.println("Case #"+T+": "+ans); T++; } /* startTime = System.nanoTime() - startTime; System.err.println("Time: "+(startTime/1000000)); */ out.flush(); } static FastScanner in = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static int oo = Integer.MAX_VALUE; static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); void ini() throws FileNotFoundException { br = new BufferedReader(new FileReader("input.txt")); } String next() { while(!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch(IOException e) {} return st.nextToken(); } String nextLine(){ try{ return br.readLine(); } catch(IOException e) { } return ""; } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int a[] = new int[n]; for(int i=0;i<n;i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } long[] readArrayL(int n) { long a[] = new long[n]; for(int i=0;i<n;i++) a[i] = nextLong(); return a; } double nextDouble() { return Double.parseDouble(next()); } double[] readArrayD(int n) { double a[] = new double[n]; for(int i=0;i<n;i++) a[i] = nextDouble(); return a; } } static final Random random = new Random(); static void ruffleSort(int[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n), temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } static void ruffleSortL(long[] a){ int n = a.length; for(int i=0;i<n;i++){ int j = random.nextInt(n); long temp = a[j]; a[j] = a[i]; a[i] = temp; } Arrays.sort(a); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
3fa34291ed831443df6d39c92b68cee7
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package Codeforces; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Solution { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } static Reader sc = new Reader(); static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String args[]) throws IOException { int t = inputInt(); while(t-->0){ int n =inputInt(); long[] a = new long[n]; long max=0; for(int i=0;i<n;i++){ a[i]=inputLong(); } Arrays.sort(a); long res=a[n-1]; long[] neg= new long[n]; for(int i=1;i<n;i++){ neg[i]=neg[i-1]+i*(a[i]-a[i-1]); res-=neg[i]; } System.out.println(res); } } public static int inputInt() throws IOException { return sc.nextInt(); } public static long inputLong() throws IOException { return sc.nextLong(); } public static double inputDouble() throws IOException { return sc.nextDouble(); } public static String inputString() throws IOException { return sc.readLine(); } public static void print(String a) throws IOException { bw.write(a); } public static void printSp(String a) throws IOException { bw.write(a + " "); } public static void println(String a) throws IOException { bw.write(a + "\n"); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
1d260941cb7f52ed2b3f60554a87c6e3
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; import java.math.*; public class GFG { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main (String[] args) { FastReader sc=new FastReader(); int n = sc.nextInt(); for(int g=0;g<n;g++){ int size=sc.nextInt(); long temp=0,temp2=0; Long b[]=new Long[size]; for(int i=0;i<size;i++){ b[i]=sc.nextLong(); } Arrays.sort(b); long sum=b[size-1]; for(int i=1;i<size;i++){ temp=(b[i]-b[i-1])*i+temp; temp2+=temp; } temp2=temp2*-1; sum+=temp2; System.out.println(sum); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
0b7b85a506700838ac56f0651cff36d3
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int T = in.nextInt(); while(T>0) { int N = in.nextInt(); List<BigInteger> mylist = new ArrayList<>(); for(int i=0;i<N;++i) { int a = in.nextInt(); mylist.add(BigInteger.valueOf(a)); } if(N==1||N==2) { System.out.println("0"); --T; continue; } Collections.sort(mylist); List<BigInteger> list = new ArrayList<>(); list.add(mylist.get(1)); for(int i=2;i<mylist.size();++i) { list.add(mylist.get(i).subtract(mylist.get(i-1))); } BigInteger ans = new BigInteger("0"); long K = list.size(); for(long i=0;i<list.size();++i) { BigInteger temp = BigInteger.valueOf(((i+1)*(K-i))-1); ans = ans.add(temp.multiply(list.get((int)i))); } ans = ans.multiply(BigInteger.valueOf(-1)); System.out.println(ans.toString()); --T; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
9cc9ba73582bf3f8009f3d71c1b01011
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class Solution { static final int MOD = (int)1e9+7; public static void main(String[] args)throws Exception { int T = nextInt(); // int T = 1; while(T-- > 0) { int n = nextInt(); // int n = 5; long[] a = new long[n]; for (int i=0;i<n;i++) { a[i] = nextLong(); } // long[] a = {0,538147868,932315946,740036786,349811835}; Arrays.sort(a); // System.out.println(Arrays.toString(a)); long sum = 0L; long value = 0L; for(int i=2;i<n;i++) { value -= (i-1) * a[i] - sum; // System.out.println(i+"\t"+sum+"\t"+value); sum += a[i-1]; } System.out.println(value); } } static void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; } static int nextInt()throws IOException{ InputStream in=System.in; int ans=0; boolean flag=true; byte b=0; boolean neg=false; while ((b>47 && b<58) || flag){ if(b==45) neg=true; if(b>=48 && b<58){ ans=ans*10+(b-48); flag=false; } b=(byte)in.read(); } if(neg) return -ans; return ans; } static long nextLong()throws IOException{ InputStream in=System.in; long ans=0; boolean flag=true; byte b=0; while ((b>47 && b<58) || flag){ if(b>=48 && b<58){ ans=ans*10+(b-48); flag=false; } b=(byte)in.read(); } return ans; } static String next()throws Exception{ StringBuilder sb=new StringBuilder(1<<16); InputStream in=System.in; byte b=0; do{ if(!isWhiteSpace(b)) sb.append((char)b); b=(byte)in.read(); }while(!isWhiteSpace(b) || sb.length()==0); return sb.toString(); } static boolean isWhiteSpace(byte b){ char ch=(char)b; return ch=='\0' || ch==' ' || ch=='\n'; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
9a595dc253ef75018cdf690d3a6d22c8
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-->0){ int n = sc.nextInt(); long[] a = new long[n]; for(int i=0;i<n;i++) a[i] = sc.nextLong(); long ans=0,sum=0; Arrays.sort(a); ans=a[n-1]; for(int i=0;i<n;i++){ ans=ans-((i*1L*a[i])-sum); sum=sum+a[i]; } System.out.println(ans); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
1c08a833b5d509a2ed88c6e26c376bb6
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.Collections; import java.io.*; import java.util.*; public class Main { static FastReader reader = new FastReader(); static OutputWriter out = new OutputWriter(System.out); public static void main(String[] args) { int tests = reader.nextInt(); for(int test = 1; test <= tests; test++) { int n = reader.nextInt(); PriorityQueue<Long> queue = new PriorityQueue<>(); for (int i = 0; i < n; i++) { queue.add(reader.nextLong()); } long res = 0; long prev = queue.poll(); long s = 0; long j = 1; while(!queue.isEmpty()) { long cur = queue.poll(); s = s + (cur - prev) * j; res += (cur - prev); res -= s; prev = cur; j++; } out.println(res); } out.flush(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public 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(char[] array) { writer.print(array); } public void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void print(int[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void print(double[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void print(long[] array) { for (int i = 0; i < array.length; i++) { if (i != 0) { writer.print(' '); } writer.print(array[i]); } } public void println(int[] array) { print(array); writer.println(); } public void println(double[] array) { print(array); writer.println(); } public void println(long[] array) { print(array); writer.println(); } public void println() { writer.println(); } public void println(Object... objects) { print(objects); writer.println(); } public void print(char i) { writer.print(i); } public void println(char i) { writer.println(i); } public void println(char[] array) { writer.println(array); } public void printf(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } public void print(long i) { writer.print(i); } public void println(long i) { writer.println(i); } public void print(int i) { writer.print(i); } public void println(int i) { writer.println(i); } public void separateLines(int[] array) { for (int i : array) { println(i); } } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
17866646a5e5756c9296b76ef9d740b1
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class c727a { //By shwetank_verma static class Point implements Comparable<Point> { int x, y; Point(int x, int y) { this.x = x; this.y = y; } public int compareTo(Point P) { return this.x - P.x; } } public static void main(String[] args) { FastReader sc=new FastReader(); int t=1; t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); } ruffleSort(a); long ans=0; ArrayList<Long> d=new ArrayList<>(); for(int i=1;i<n;i++) { ans+=(a[i]-a[i-1]); d.add((long)a[i]-a[i-1]); } for(int i=0;i<d.size();i++) { d.set(i, (long)d.get(i)*(i+1)); } for(int i=0;i<d.size();i++) { ans-=(long)(d.size()-i)*d.get(i); } if(ans!=0) System.out.println(ans); else System.out.println(0); } } static void ruffleSort(long[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { long oi=r.nextInt(n), temp=a[i]; a[i]=a[(int)oi]; a[(int)oi]=temp; } Arrays.sort(a); } static void ruffleSort(int[] a) { int n=a.length; Random r=new Random(); for (int i=0; i<a.length; i++) { int oi=r.nextInt(n), temp=a[i]; a[i]=a[oi]; a[oi]=temp; } Arrays.sort(a); } static void ruffleSort(char[] c) { int n=c.length; PriorityQueue<Character> pq=new PriorityQueue<>(); for(char cc:c) { pq.add(cc); } for(int i=0;i<n;i++) { c[i]=pq.poll(); } } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int mod=1000000007; static boolean primes[]=new boolean[1000007]; static ArrayList<Integer> b=new ArrayList<>(); static boolean seive(int n){ Arrays.fill(primes,true); primes[0]=primes[1]=false; for(int i=2;i*i<=n;i++){ if(primes[i]==true){ for(int p=i*i;p<=n;p+=i){ primes[p]=false; } } } if(n<1000007){ for(int i=2;i<=n;i++) { if(primes[i]) b.add(i); } return primes[n]; } return false; } static int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b); } static long GCD(long a,long b){ if(b==0) return a; return GCD(b,a%b); } static ArrayList<Integer> segseive(int l,int r){ ArrayList<Integer> isprime=new ArrayList<Integer>(); boolean p[]=new boolean[r-l+1]; Arrays.fill(p, true); for(int i=0;b.get(i)*b.get(i)<=r;i++) { int currprime=b.get(i); int base=(l/currprime)*currprime; if(base<l) { base+=currprime; } for(int j=base;j<=r;j+=currprime) { p[j-l]=false; } if(base==currprime) { p[base-l]=true; } } for(int i=0;i<=r-l;i++) { if(p[i]) isprime.add(i+l); } return isprime; } static int LowerBound(int a[], int x) { // x is the target value or key int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } static int UpperBound(int a[], int x) {// x is the key or target value int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
2bdd6dcfaa4fcfbc98b8129c8f351890
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int TT = sc.nextInt(); while (TT-- > 0) { int n = sc.nextInt(); int d[] = sc.readArray(n); if (n < 3) { out.println(0); continue; } sort(d); long pre[] = new long[n]; for (int i = 1; i < n; i++) pre[i] = pre[i - 1] + d[i]; long ans = d[n - 1]; for (int i = 1; i < n; i++) ans -= (long)i * d[i] - pre[i - 1]; out.println(ans); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
7380797823b9fcfb86c39ca31d4dc368
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void main(String[] args) { FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); int TT = sc.nextInt(); while (TT-- > 0) { int n = sc.nextInt(); int d[] = sc.readArray(n); if (n < 3) { out.println(0); continue; } sort(d); long pre[] = new long[n]; for (int i = 1; i < n; i++) pre[i] = pre[i - 1] + d[i]; long ans = d[n - 1]; for (int i = 1; i < n; i++) ans -= (long)i * d[i] - pre[i - 1]; out.println(ans); } out.close(); } static void sort(int[] a) { ArrayList<Integer> l = new ArrayList<>(); for (int i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
9316966bbc2c0f9b8a73ba695bc70b39
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
/* ¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶ ¶¶¶¶¶¶¶ ¶¶¶¶ ¶¶¶¶ ¶¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶ ¶¶ ¶¶ ¶¶ ¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶ ¶¶ ¶¶ ¶¶¶¶ ¶¶¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶¶¶ ¶¶¶¶¶ ¶¶¶ ¶¶¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶¶¶ ¶¶¶ ¶¶¶ ¶¶ ¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶¶ ¶¶ ¶¶¶¶ ¶¶¶¶¶ ¶¶ ¶¶¶¶¶¶¶ ¶¶¶ ¶¶¶¶¶¶¶ ¶¶ ¶¶¶¶¶¶ ¶¶ ¶¶ ¶¶ ¶¶¶ ¶¶¶¶¶ ¶¶¶ ¶¶ ¶¶ ¶¶ ¶¶¶ ¶¶¶¶ ¶¶ ¶¶¶¶¶¶¶ ¶¶ ¶¶¶¶ ¶¶¶ ¶¶ ¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶¶ ¶¶ ¶¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶ ¶¶¶¶ ¶¶¶¶¶ ¶¶¶¶¶ ¶¶¶ ¶¶ ¶¶¶¶¶¶ ¶¶¶ ¶¶¶¶¶¶ ¶¶¶ ¶¶ ¶¶ ¶¶¶ ¶¶¶¶¶¶ ¶¶¶¶¶¶ ¶¶ ¶¶¶¶¶¶¶¶¶¶¶ ¶¶ ¶¶¶¶¶¶ ¶¶ ¶¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶¶ ¶¶¶¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶ ¶¶¶¶¶ ¶¶¶¶¶ ¶¶ ¶¶¶¶¶¶¶¶¶¶¶¶¶ ¶¶ ¶¶¶¶¶ ¶¶¶¶¶¶¶¶¶¶ ¶¶ ¶¶ ¶¶¶¶¶¶¶¶¶ ¶¶ ¶¶¶¶¶¶¶ ¶¶¶¶¶¶¶¶ ¶¶ ¶¶¶ ¶¶¶¶¶ ¶¶¶¶¶¶¶¶¶¶¶¶¶¶¶ ¶¶¶¶¶ ¶¶¶ ¶¶ ¶¶¶ ¶¶¶¶¶¶¶¶¶ ¶¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶ ¶¶¶¶ ¶¶¶¶ */ import java.lang.*; import java.util.*; import java.io.*; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.max; import static java.lang.Math.ceil; import static java.lang.Math.floor; import java.math.BigInteger; public class C { final static int mod = (int)(1e9 + 7); static int factors[]; public static void main(String[] args) { FastReader fs = new FastReader(); int testcase = 1; testcase = fs.nextInt(); while (testcase-- > 0) { solve(fs); } } public static void solve(FastReader fs) { int n = fs.nextInt(); int arr[] = fs.readArray(n); sort(arr); //System.out.println(Arrays.toString(arr)); long ans = 0L, mn = 0; for (int i = 1; i < n; i++) { long diff = arr[i] - arr[i - 1]; mn = (i) * -diff + mn; ans += mn; } //debug("ans", ans); ans += arr[n - 1]; //debug("arr[n-1]", arr[n - 1]); System.out.println(ans); } //template function //----------------------------------------------------------------- static void swap(int a[], int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } static void seive() { int range = 1000000; factors = new int[range + 1]; factors[0] = 1; factors[1] = 1; for (int i = 2; i * i <= range; i++) { if (factors[i] == 0) { for (int j = i * i; j <= range; j += i) { factors[j] = 1; } } } } static boolean isPrime(int num) { return factors[num] == 0; } static long power(long a, long b) { long result = 1L; while (b > 0) { if (b % 2 == 1) { result *= a; } a *= a; b /= 2; } return result; } static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } static void sort(int a[]) { ArrayList<Integer> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) ans.add(a[i]); Collections.sort(ans); for (int i = 0; i < a.length; i++) a[i] = ans.get(i); } static void sortL(long a[]) { ArrayList<Long> ans = new ArrayList<>(); for (int i = 0; i < a.length; i++) ans.add(a[i]); Collections.sort(ans); for (int i = 0; i < a.length; i++) a[i] = ans.get(i); } static <T> void debug(String str, T value) { System.out.println(str + " -> {" + value + "}"); } //---------------------------------------------------------------------------------------------------- //IO operation 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()); } int[] readArray(int n) { int arr[] = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } long[] readArrayL(int n) { long arr[] = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
efcf930058d4f4e6680c8a2ccff00a44
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Long> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Long> l = new ArrayList<>(); for (long p=2; p*p<=n; p++) { if (prime[(int)(p)] == true) { for(long i=p*p; i<=n; i += p) { prime[(int)(p)] = false; } } } for (long p=2; p<=n; p++) { if (prime[(int)(p)] == true) { l.add(p); } } return l; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(long a[], long x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(long a[], long x) { int l=-1, r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); // Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); long[] a = sc.longReadArray(n); if(n == 1) { fout.println(0); } else { Arrays.sort(a); long[] diff = new long[n-1]; for(int i = 0;i<n-1;i++) diff[i] = (a[i+1] - a[i]); long ans = 0; for(int i = 0;i<n-1;i++) { ans -= (diff[i] * (i + 1) * (n - 1 - i)); } for(long it : diff) ans += it; fout.println(ans); } } fout.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
50bdb5a96c0363c773389b04da0b6b05
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import static java.lang.Math.*; import static java.lang.System.out; import java.util.*; import java.io.File; import java.io.PrintStream; import java.io.PrintWriter; import java.math.BigInteger; public class Main { /* 10^(7) = 1s. * ceilVal = (a+b-1) / b */ static final int mod = 1000000007; static final long temp = 998244353; static final long MOD = 1000000007; static final long M = (long)1e9+7; static class Pair implements Comparable<Pair> { int first, second; public Pair(int first, int second) { this.first = first; this.second = second; } public int compareTo(Pair ob) { return (int)(first - ob.first); } } static class Tuple implements Comparable<Tuple> { int first, second,third; public Tuple(int first, int second, int third) { this.first = first; this.second = second; this.third = third; } public int compareTo(Tuple o) { return (int)(o.third - this.third); } } public static class DSU { int[] parent; int[] rank; //Size of the trees is used as the rank public DSU(int n) { parent = new int[n]; rank = new int[n]; Arrays.fill(parent, -1); Arrays.fill(rank, 1); } public int find(int i) //finding through path compression { return parent[i] < 0 ? i : (parent[i] = find(parent[i])); } public boolean union(int a, int b) //Union Find by Rank { a = find(a); b = find(b); if(a == b) return false; //if they are already connected we exit by returning false. // if a's parent is less than b's parent if(rank[a] < rank[b]) { //then move a under b parent[a] = b; } //else if rank of j's parent is less than i's parent else if(rank[a] > rank[b]) { //then move b under a parent[b] = a; } //if both have the same rank. else { //move a under b (it doesnt matter if its the other way around. parent[b] = a; rank[a] = 1 + rank[a]; } return true; } } static class Reader { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) throws IOException { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long[] longReadArray(int n) throws IOException { long[] a=new long[n]; for (int i=0; i<n; i++) a[i]=nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static int gcd(int a, int b) { if(b == 0) return a; else return gcd(b,a%b); } public static long lcm(long a, long b) { return (a / LongGCD(a, b)) * b; } public static long LongGCD(long a, long b) { if(b == 0) return a; else return LongGCD(b,a%b); } public static long LongLCM(long a, long b) { return (a / LongGCD(a, b)) * b; } //Count the number of coprime's upto N public static long phi(long n) //euler totient/phi function { long ans = n; // for(long i = 2;i*i<=n;i++) // { // if(n%i == 0) // { // while(n%i == 0) n/=i; // ans -= (ans/i); // } // } // // if(n > 1) // { // ans -= (ans/n); // } for(long i = 2;i<=n;i++) { if(isPrime(i)) { ans -= (ans/i); } } return ans; } public static long fastPow(long x, long n) { if(n == 0) return 1; else if(n%2 == 0) return fastPow(x*x,n/2); else return x*fastPow(x*x,(n-1)/2); } public static long modPow(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if (y % 2 == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } static long modInverse(long n, long p) { return modPow(n, p - 2, p); } // Returns nCr % p using Fermat's little theorem. public static long nCrModP(long n, long r,long p) { if (n<r) return 0; if (r == 0) return 1; long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (int i = 1; i <= n; i++) fac[i] = fac[i - 1] * i % p; return (fac[(int)(n)] * modInverse(fac[(int)(r)], p) % p * modInverse(fac[(int)(n - r)], p) % p) % p; } public static long fact(long n) { long[] fac = new long[(int)(n) + 1]; fac[0] = 1; for (long i = 1; i <= n; i++) fac[(int)(i)] = fac[(int)(i - 1)] * i; return fac[(int)(n)]; } public static long nCr(long n, long k) { long ans = 1; for(long i = 0;i<k;i++) { ans *= (n-i); ans /= (i+1); } return ans; } //Modular Operations for Addition and Multiplication. public static long perfomMod(long x) { return ((x%M + M)%M); } public static long addMod(long a, long b) { return perfomMod(perfomMod(a)+perfomMod(b)); } public static long subMod(long a, long b) { return perfomMod(perfomMod(a)-perfomMod(b)); } public static long mulMod(long a, long b) { return perfomMod(perfomMod(a)*perfomMod(b)); } public static boolean isPrime(long n) { if(n == 1) { return false; } for(int i = 2;i*i<=n;i++) { if(n%i == 0) { return false; } } return true; } public static List<Long> SieveList(int n) { boolean prime[] = new boolean[(int)(n+1)]; Arrays.fill(prime, true); List<Long> l = new ArrayList<>(); for (long p=2; p*p<=n; p++) { if (prime[(int)(p)] == true) { for(long i=p*p; i<=n; i += p) { prime[(int)(p)] = false; } } } for (long p=2; p<=n; p++) { if (prime[(int)(p)] == true) { l.add(p); } } return l; } public static long log2(long n) { long ans = (long)(log(n)/log(2)); return ans; } public static boolean isPow2(long n) { return (n != 0 && ((n & (n-1))) == 0); } public static boolean isSq(int x) { long s = (long)Math.round(Math.sqrt(x)); return s*s==x; } /* * * >= <= 0 1 2 3 4 5 6 7 5 5 5 6 6 6 7 7 lower_bound for 6 at index 3 (>=) upper_bound for 6 at index 6(To get six reduce by one) (<=) */ public static int LowerBound(long a[], long x) { int l=-1,r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]>=x) r=m; else l=m; } return r; } public static int UpperBound(long a[], long x) { int l=-1, r=a.length; while(l+1<r) { int m=(l+r)>>>1; if(a[m]<=x) l=m; else r=m; } return l+1; } public static void Sort(long[] a) { List<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); // Collections.reverse(l); //Use to Sort decreasingly for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void ssort(char[] a) { List<Character> l = new ArrayList<>(); for (char i : a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } public static void main(String[] args) throws Exception { Reader sc = new Reader(); PrintWriter fout = new PrintWriter(System.out); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); long[] a = sc.longReadArray(n); if(n == 1) { fout.println(0); } else { Sort(a); long[] diff = new long[n-1]; for(int i = 0;i<n-1;i++) diff[i] = (a[i+1] - a[i]); long ans = 0; for(int i = 0;i<n-1;i++) { ans -= (diff[i] * (i + 1) * (n - 1 - i)); } for(long it : diff) ans += it; fout.println(ans); } } fout.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
127cf1622a37fbcd175c7dcab7567921
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; public class Main{ public static void main(String []args)throws Exception{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); int T=Integer.parseInt(br.readLine()); while(T-->0){ int n=Integer.parseInt(br.readLine()); long a[]=new long[n]; String s[]=br.readLine().split(" "); for(int i=0;i<n;i++) a[i]=Integer.parseInt(s[i]); Arrays.sort(a); if(n<=2){ bw.write(0+"\n"); continue; } long ans=0,c=1; long sum=0; for(int i=2;i<n;i++){ ans+=sum-(a[i]*c); sum+=a[i-1]; c++; } bw.write(ans+"\n"); } bw.flush(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
865dc8fa28231c998f68e64806036c9a
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Sweetgraphs { public static void main(String[] args) { // TODO Auto-generated method stub fastReader sc = new fastReader(); int t = sc.nextInt(); int i; for(i=0; i<t; i++) { int n = sc.nextInt(); long arr[] = new long[n]; int j; for(j=0; j<n; j++) { arr[j] = sc.nextLong(); } System.out.println(solve(arr)); } } static long solve(long[] arr) { int i; int n = arr.length; long total=0; long sum=0; Arrays.sort(arr); int count=0; for(i=0; i<n; i++) { total += count*(arr[i]) - sum; sum += arr[i]; count++; } total = arr[n-1] - total; return total; } } class fastReader{ BufferedReader br; StringTokenizer st; public fastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } // next word method public String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } // next Integer method public int nextInt() { return Integer.parseInt(next()); } // next long method public long nextLong() { return Long.parseLong(next()); } // next float method public float nextFloat() { return Float.parseFloat(next()); } // next Double method public double nextDouble() { return Double.parseDouble(next()); } // next byte Method public byte nextByte() { return Byte.parseByte(next()); } // next Line method public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
ac6d80b2c4bf10cf5d86633ffb4808d9
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main{ static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] nextArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextArray(long n) { long[] a = new long[(int) n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } long nextLong() { return Long.parseLong(next()); } } static class FastWriter extends PrintWriter { FastWriter(){ super(System.out); } void println(int[] array) { for(int i=0; i<array.length; i++) { print(array[i]+" "); } println(); } void println(long [] array) { for(int i=0; i<array.length; i++) { print(array[i]+" "); } println(); } } static int MOD=998244353; public static void main(String[] args){ FastScanner in = new FastScanner(); FastWriter out = new FastWriter(); int t=in.nextInt(); //int t=1; while (t-->0){ int n=in.nextInt(); Integer[] ar=new Integer[n]; for (int i = 0; i < n; i++) { ar[i]=in.nextInt(); } if(n==1||n==2){ out.println(0); }else{ long ans=0,curSum=0; Arrays.sort(ar); for(int i=2;i<n;i++){ curSum+=ar[i-2]; ans+=curSum- (long) (i - 1) *ar[i]; } out.println(ans); } } out.close(); } //Arrays.sort(a, (o1, o2) -> (o1[0] - o2[0])); static int diff(int num1,int num2) { String s1 = String.valueOf(num1); String s2 = String.valueOf(num2); if (s1.length() < s2.length()) { s1 = "0" + s1; }else if(s1.length()>s2.length()){ s2="0"+s2; } int cnt=0; for (int i = 0; i < s1.length(); i++) { if(s1.charAt(i)!=s2.charAt(i)){ cnt++; } } return cnt; } static int totalPrimeFactors(int n) { int cnt=0; while (n%2==0) { cnt++; n /= 2; } int num= (int) Math.sqrt(n); for (int i = 3; i <= num; i+= 2) { while (n%i == 0) { cnt++; n /= i; num=(int)Math.sqrt(n); } } if (n > 2){ cnt++; } return cnt; } static char get(int i){ return (char)(i+'a'); } static boolean distinct(int num){ HashSet<Integer> set=new HashSet<>(); int len=String.valueOf(num).length(); while (num!=0){ set.add(num%10); num/=10; } return set.size()==len; } static int maxSubArraySum(int a[],int st,int en) { int max_s = Integer.MIN_VALUE, max_e = 0,ind=0,ind1=1; for (int i = st; i <= en; i++) { max_e+= a[i]; if (max_s < max_e){ max_s = max_e; ind=ind1; } if (max_e < 0){ max_e = 0; ind1=i+1; } } if(st==0){ return max_s; } if(ind==1){ return a[0]+2*max_s; }else { return 2*max_s+maxSubArraySum(a,0,ind-1); } //return max_s; } static void segmentedSieve(ArrayList<Integer> res,int low, int high) { if(low < 2){ low = 2; } ArrayList<Integer> prime = new ArrayList<>(); simpleSieve(high, prime); boolean[] mark = new boolean[high - low + 1]; for (int i = 0; i < mark.length; i++){ mark[i] = true; } for (int i = 0; i < prime.size(); i++) { int loLim = (low / prime.get(i)) * prime.get(i); if (loLim < low){ loLim += prime.get(i); } if (loLim == prime.get(i)){ loLim += prime.get(i); } for (int j = loLim; j <= high; j += prime.get(i)) { mark[j - low] = false; } } for (int i = low; i <= high; i++) { if (mark[i - low]){ res.add(i); } } } static void simpleSieve(int limit, ArrayList<Integer> prime) { int bound = (int)Math.sqrt(limit); boolean[] mark = new boolean[bound + 1]; for (int i = 0; i <= bound; i++){ mark[i] = true; } for (int i = 2; i * i <= bound; i++) { if (mark[i]) { for (int j = i * i; j <= bound; j += i){ mark[j] = false; } } } for (int i = 2; i <= bound; i++) { if (mark[i]){ prime.add(i); } } } static int highestPowerOf2(int n) { if (n < 1){ return 0; } int res = 1; for (int i = 0; i < 8 * Integer.BYTES; i++) { int curr = 1 << i; if (curr > n){ break; } res = curr; } return res; } static int reduceFraction(int x, int y) { int d= gcd(x, y); return x/d+y/d; } static boolean subset(int[] ar,int n,int sum){ if(sum==0){ return true; } if(n<0||sum<0){ return false; } return subset(ar,n-1,sum)||subset(ar,n-1,sum-ar[n]); } static boolean isPrime(int n){ if(n<=1) return false; for(int i = 2;i<=Math.sqrt(n);i++){ if (n % i == 0) return false; } return true; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static long gcd(long a, long b) { if (b == 0) return a; return gcd(b, a % b); } static long lcm(long a, long b) { return (a * b) / gcd(a, b); } static int lcm(int a, int b) { return (a * b) / gcd(a, b); } static boolean isPowerOfTwo(int n) { if(n==0){ return false; } while (n%2==0){ n/=2; } return n==1; } static boolean isPerfectSquare(int x){ if (x >= 0) { int sr = (int)Math.sqrt(x); return ((sr * sr) == x); } return false; } static int lower_bound(int[] arr, int x) { int low_limit = 0, high_limit = arr.length, mid; while (low_limit < high_limit) { mid = (low_limit + high_limit) / 2; if (arr[mid] >= x){ high_limit = mid; }else{ low_limit = mid + 1; } } return low_limit; } static int upper_bound(int[] arr, int x) { int low_limit = 0, high_limit = arr.length, mid; while (low_limit < high_limit) { mid = (low_limit + high_limit) / 2; if (arr[mid] > x){ high_limit = mid; }else{ low_limit = mid + 1; } } return low_limit; } static int binarySearch(int[] ar,int n,int num){ int low=0,high=n-1; while (low<=high){ int mid=(low+high)/2; if(ar[mid]==num){ return mid; }else if(ar[mid]>num){ high=mid-1; }else { low=mid+1; } } return -1; } static int fib(int n) { long F[][] = new long[][]{{1,1},{1,0}}; if (n == 0){ return 0; } power(F, n-1); return (int)F[0][0]; } static void multiply(long F[][], long M[][]) { long x = (F[0][0]*M[0][0])%1000000007 + (F[0][1]*M[1][0])%1000000007; long y = (F[0][0]*M[0][1])%1000000007 + (F[0][1]*M[1][1])%1000000007; long z = (F[1][0]*M[0][0])%1000000007 + (F[1][1]*M[1][0])%1000000007; long w = (F[1][0]*M[0][1])%1000000007 + (F[1][1]*M[1][1])%1000000007; F[0][0] = x%1000000007; F[0][1] = y%1000000007; F[1][0] = z%1000000007; F[1][1] = w%1000000007; } static void power(long F[][], int n) { if( n == 0 || n == 1){ return; } long M[][] = new long[][]{{1,1},{1,0}}; power(F, n/2); multiply(F, F); if (n%2 != 0){ multiply(F, M); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
18d4d1e92cd55d4b188e4976d2e01d57
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
// package com.company; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class P3 { public static void main(String[] args) { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner scan = new Scanner(System.in); int t = scan.nextInt(); while(t>0){ t--; int n = scan.nextInt(); long[] arr = new long[n]; long[] pref = new long[n]; for(int i = 0;i<n;i++){ arr[i] = scan.nextLong(); } Arrays.sort(arr); for(int i = 1;i<n;i++){ pref[i] += pref[i-1] + arr[i]; } long count = 0; for(int i = 2;i<n;i++){ count += pref[i-2] - (i-1) * arr[i]; } System.out.println(count); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
58b728660327011434bb985d8973aae5
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.io.*; public class CodeforcesRound728 { static FastReader sc = new FastReader(); public static void main(String[] args) throws IOException { try { int t = sc.nextInt(); while (t-- > 0) { B(); } } catch (Exception e) { return; } } static void B() { int n = sc.nextInt(); long a[] = sc.readLongArray(n); long summ = 0, val = 0; Arrays.sort(a); for (int i = 2; i < n; i++) { summ += a[i - 2]; val -= (a[i] * (i - 1)); val += summ; } System.out.println(val); } static void A() { int n = sc.nextInt(); int a[] = new int[n]; if (n % 2 != 0) { if (n == 3) { System.out.println("3 1 2"); return; } else { System.out.print("3 1 2 "); for (int i = 3; i < n; i++) { a[i] = i + 1; } for (int i = 3; i < n - 1; i += 2) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } for (int i = 3; i < n; i++) { System.out.print(a[i] + " "); } return; } } else { for (int i = 0; i < n; i++) { a[i] = i + 1; } for (int i = 0; i < n - 1; i += 2) { int temp = a[i]; a[i] = a[i + 1]; a[i + 1] = temp; } } for (int i : a) { System.out.print(i + " "); } System.out.println(); } static boolean[] seiveOfEratosthenes(int n) { boolean[] isPrime = new boolean[n + 1]; Arrays.fill(isPrime, true); for (int i = 2; i * i <= n; i++) { for (int j = i * i; j <= n; j += i) { isPrime[j] = false; } } return isPrime; } static boolean isPrime(long n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } } 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()); } int[] readIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = Integer.parseInt(next()); } return a; } void printIntArray(int a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } long[] readLongArray(int n) { long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = Long.parseLong(next()); } return a; } void printLongArray(long a[]) { for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
012ca3fdb5d387e95c405cb9786733df
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.math.BigInteger; public final class A { static PrintWriter out = new PrintWriter(System.out); static StringBuilder ans=new StringBuilder(); static FastReader in=new FastReader(); static ArrayList<ArrayList<Integer>> g; static long mod=(long)1e9+7,INF=Long.MAX_VALUE; static boolean set[],col[]; static int par[],tot[],partial[]; static int D[],P[][]; static long dp[][],max=0; static long seg[]; //static pair moves[]= {new pair(-1,0),new pair(1,0), new pair(0,-1), new pair(0,1)}; public static void main(String args[])throws IOException { int T=i(); outer:while(T-->0) { int N=i(); long A[]=inputLong(N); sort(A); long s=0; long sum=A[N-1]; for(int i=1; i<N; i++) { long a=i; long b=N-i; long c=A[i]-A[i-1]; s+=a*b*c; // System.out.println(a+" "+b+" "+c); } out.println(sum-s); } out.close(); } static long f1(long a,long A[],long bits[],long sum) { long s=A.length; s=mul(s,a); s=(s+(sum%mod))%mod; long p=1L; for(long x:bits) { if((a&p)!=0)s=((s-mul(x,p))+mod)%mod; p<<=1; } return s; } static long f2(long a,long A[],long bits[]) { long s=0; long p=1L; for(long x:bits) { if((a&p)!=0) { s=(s+mul(p,x))%mod; } p<<=1; } return s; } static long f(long x1,long y1,long x2,long y2) { return Math.abs(x1-x2)+Math.abs(y1-y2); } static long f(long x,long max,long s) { long l=-1,r=(x/s)+1; while(r-l>1) { long m=(l+r)/2; if(x-m*s>max)l=m; else r=m; } return l+1; } static int f(long A[],long x) { int l=-1,r=A.length; while(r-l>1) { int m=(l+r)/2; if(A[m]>=x)r=m; else l=m; } return r; } static void build(int v,int tl,int tr,long A[]) { if(tl==tr) { seg[v]=A[tl]; return; } int tm=(tl+tr)/2; build(v*2,tl,tm,A); build(v*2+1,tm+1,tr,A); seg[v]=GCD(seg[v*2],seg[v*2+1]); } static long ask(int v,int tl,int tr,int l,int r) { if(tl==l && tr==r)return seg[v]; int tm=(tl+tr)/2; if(r<=tm) { return ask(v*2,tl,tm,l,r); } else if(l>tm) { return ask(v*2+1,tm+1,tr,l,r); } else { return GCD(ask(v*2,tl,tm,l,tm),ask(v*2+1,tm+1,tr,tm+1,r)); } } static int bin(int x,ArrayList<Integer> A) { int l=0,r=A.size()-1; while(l<=r) { int m=(l+r)/2; int a=A.get(m); if(a==x)return m; if(a<x)l=m+1; else r=m-1; } return 0; } static int left(int x,ArrayList<Integer> A) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; int a=A.get(m); if(a<=x)l=m; else r=m; } return l; } static int right(int x,ArrayList<Integer> A) { int l=-1,r=A.size(); while(r-l>1) { int m=(l+r)/2; int a=A.get(m); if(a<x)l=m; else r=m; } return r; } static boolean equal(long A[],long B[]) { for(int i=0; i<A.length; i++)if(A[i]!=B[i])return false; return true; } static int max(int a ,int b,int c,int d) { a=Math.max(a, b); c=Math.max(c,d); return Math.max(a, c); } static int min(int a ,int b,int c,int d) { a=Math.min(a, b); c=Math.min(c,d); return Math.min(a, c); } static HashMap<Integer,Integer> Hash(int A[]) { HashMap<Integer,Integer> mp=new HashMap<>(); for(int a:A) { int f=mp.getOrDefault(a,0)+1; mp.put(a, f); } return mp; } static long mul(long a, long b) { return ( a %mod * 1L * b%mod )%mod; } static void swap(int A[],int a,int b) { int t=A[a]; A[a]=A[b]; A[b]=t; } static int find(int a) { if(par[a]<0)return a; return par[a]=find(par[a]); } static void union(int a,int b) { a=find(a); b=find(b); if(a!=b) { par[a]+=par[b]; par[b]=a; } } static boolean isSorted(int A[]) { for(int i=1; i<A.length; i++) { if(A[i]<A[i-1])return false; } return true; } static boolean isDivisible(StringBuilder X,int i,long num) { long r=0; for(; i<X.length(); i++) { r=r*10+(X.charAt(i)-'0'); r=r%num; } return r==0; } static int lower_Bound(int A[],int low,int high, int x) { if (low > high) if (x >= A[high]) return A[high]; int mid = (low + high) / 2; if (A[mid] == x) return A[mid]; if (mid > 0 && A[mid - 1] <= x && x < A[mid]) return A[mid - 1]; if (x < A[mid]) return lower_Bound( A, low, mid - 1, x); return lower_Bound(A, mid + 1, high, x); } static String f(String A) { String X=""; for(int i=A.length()-1; i>=0; i--) { int c=A.charAt(i)-'0'; X+=(c+1)%2; } return X; } static void sort(long[] a) //check for long { ArrayList<Long> l=new ArrayList<>(); for (long i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static String swap(String X,int i,int j) { char ch[]=X.toCharArray(); char a=ch[i]; ch[i]=ch[j]; ch[j]=a; return new String(ch); } static int sD(long n) { if (n % 2 == 0 ) return 2; for (int i = 3; i * i <= n; i += 2) { if (n % i == 0 ) return i; } return (int)n; } static void setGraph(int N) { tot=new int[N+1]; partial=new int[N+1]; D=new int[N+1]; P=new int[N+1][(int)(Math.log(N)+10)]; set=new boolean[N+1]; g=new ArrayList<ArrayList<Integer>>(); for(int i=0; i<=N; i++) { g.add(new ArrayList<>()); D[i]=0; //D2[i]=INF; } } static long pow(long a,long b) { //long mod=1000000007; long pow=1; long x=a; while(b!=0) { if((b&1)!=0)pow=(pow*x)%mod; x=(x*x)%mod; b/=2; } return pow; } static long toggleBits(long x)//one's complement || Toggle bits { int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1; return ((1<<n)-1)^x; } static int countBits(long a) { return (int)(Math.log(a)/Math.log(2)+1); } static long fact(long N) { long n=2; if(N<=1)return 1; else { for(int i=3; i<=N; i++)n=(n*i)%mod; } return n; } static int kadane(int A[]) { int lsum=A[0],gsum=A[0]; for(int i=1; i<A.length; i++) { lsum=Math.max(lsum+A[i],A[i]); gsum=Math.max(gsum,lsum); } return gsum; } static void sort(int[] a) { ArrayList<Integer> l=new ArrayList<>(); for (int i:a) l.add(i); Collections.sort(l); for (int i=0; i<a.length; i++) a[i]=l.get(i); } static boolean isPrime(long N) { if (N<=1) return false; if (N<=3) return true; if (N%2 == 0 || N%3 == 0) return false; for (int i=5; i*i<=N; i=i+6) if (N%i == 0 || N%(i+2) == 0) return false; return true; } static void print(char A[]) { for(char c:A)System.out.print(c+" "); System.out.println(); } static void print(boolean A[]) { for(boolean c:A)System.out.print(c+" "); System.out.println(); } static void print(int A[]) { for(int a:A)System.out.print(a+" "); System.out.println(); } static void print(long A[]) { for(long i:A)System.out.print(i+ " "); System.out.println(); } static void print(ArrayList<Integer> A) { for(int a:A)System.out.print(a+" "); System.out.println(); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static int[] input(int N){ int A[]=new int[N]; for(int i=0; i<N; i++) { A[i]=in.nextInt(); } return A; } static long[] inputLong(int N) { long A[]=new long[N]; for(int i=0; i<A.length; i++)A[i]=in.nextLong(); return A; } static long GCD(long a,long b) { if(b==0) { return a; } else return GCD(b,a%b ); } } //class edge //{ // int s,max; // edge(int s,int max) // { // this.s=s; // this.max=max; // } //} //Code For FastReader //Code For FastReader //Code For FastReader //Code For FastReader class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } String next() { while(st==null || !st.hasMoreElements()) { try { st=new StringTokenizer(br.readLine()); } catch(IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str=""; try { str=br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
2bc3074ca09ec7b21c062b69e3ebc10a
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static int i, j, k, n, m, t, y, x, sum = 0; static long mod = 1000000007; static FastScanner fs = new FastScanner(); static PrintWriter out = new PrintWriter(System.out); static String str; static long ans; public static void main(String[] args) { t = fs.nextInt(); while (t-- > 0) { n = fs.nextInt(); long[] arr = new long[n]; for(i=0;i<n;i++) arr[i]=fs.nextLong(); ruffleSort(arr); ans = 0; long sum=0; j=1; for(i =2;i<n;i++){ ans-=((arr[i]*j)-sum); sum+=arr[j++]; } out.println(ans); } out.close(); } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } static void ruffleSort(int[] a) { //ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n), temp = a[i]; a[i] = a[oi]; a[oi] = temp; } //then sort Arrays.sort(a); } static void ruffleSort(long[] a) { //ruffle int n = a.length; Random r = new Random(); for (int i = 0; i < a.length; i++) { int oi = r.nextInt(n); long temp = a[i]; a[i] = a[oi]; a[oi] = temp; } Arrays.sort(a); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } static class Pair implements Comparable<Pair> { long first, second; public Pair(long first, long second) { this.first = first; this.second = second; } @Override public int compareTo(Pair o) { return Long.compare(first, o.first); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
5d838f6713cc8de83c2b8d0129c32768
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.StringTokenizer; public class C { public static void main(String[] args) { FastScanner fs = new FastScanner(); int t = fs.nextInt(); while (t-- > 0) { int n = fs.nextInt(); long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = fs.nextLong(); } Arrays.sort(arr); long aws = 0, summ = 0; for (int i = 2; i < n; i++) { summ += arr[i - 2]; aws -= ((long) arr[i] * (i - 1)); aws += summ; } System.out.println(aws); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
5e70ea4e50645d8bfc1b6eb313ebbc30
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.lang.*; import java.util.*; import java.io.*; public class Main { static void deal(int n,int[] arr) { if(n<=2) { out.println(0); return; } ArrayList<Integer> list = new ArrayList<>(n); for(int i=0;i<n;i++) list.add(arr[i]); Collections.sort(list); long sum = 0; for(int i=0;i<n-1;i++) { long d = (long)list.get(i+1)-list.get(i); sum += d*(i+1)*(n-i-1); } sum = (long)list.get(n-1)-sum; out.println(sum); return; } public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int t = sc.nextInt(); for(int i=0;i<t;i++) { int n = sc.nextInt(); int[] arr = new int[n]; for(int j=0;j<n;j++) arr[j] = sc.nextInt(); deal(n,arr); } out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
25ebf2f6b20e257331e56b2095309628
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class contest728 { public static void main(String[] args) { FastScanner fs = new FastScanner(); int T = 1; T=fs.nextInt(); for (int tt = 0; tt < T; tt++) { int n= fs.nextInt(); long arr[] = new long[n]; for(int i=0;i<n;i++){ arr[i] =fs.nextLong(); } sort(arr); long ways=0; long diff=0; for(int i=0;i<n;i++){ if(i==0||i==1){continue;} long prev=arr[i-2]; ways= (ways-(arr[i]*(i-1))); diff= diff+prev; ways= ways+diff; } System.out.println(ways); } } static void sort(long[] a) { ArrayList<Long> l = new ArrayList<>(); for (long i : a) l.add(i); Collections.sort(l); for (int i = 0; i < a.length; i++) a[i] = l.get(i); } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
650f27eae65cf8b8af80d5502975048a
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class Main { private static int inputN; private static ArrayList<Long> weights = new ArrayList<>(); private static long[] accumulatedSum = new long[100000]; private static long[] reverseAccumulatedSum = new long[100000]; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int testCase = Integer.parseInt(br.readLine().trim()); while(testCase-- > 0) { inputN = Integer.parseInt(br.readLine().trim()); weights.clear(); StringTokenizer st = new StringTokenizer(br.readLine().trim()); for(int i = 0; i < inputN; ++i) { weights.add(Long.parseLong(st.nextToken())); } Collections.sort(weights); accumulatedSum[0] = 0; for(int i = 1; i < inputN; ++i) { accumulatedSum[i] = weights.get(i) + accumulatedSum[i-1]; } reverseAccumulatedSum[inputN-1] = weights.get(inputN-1); for(int i = inputN-2; i >= 0; --i) { reverseAccumulatedSum[i] = weights.get(i) + reverseAccumulatedSum[i+1]; } long resultVal = 0; for(int i = 2; i < inputN; ++i) { resultVal += -1*(reverseAccumulatedSum[i] - accumulatedSum[i-2]); } System.out.println(resultVal); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
679b11de4a9c20b51c01936108493401
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public final class Solution { static PrintWriter out = new PrintWriter(System.out); static FastReader in = new FastReader(); static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(1, 0), new Pair(0, -1), new Pair(0, 1)}; public static void main(String[] args) { int tt = i(); out: while (tt-- > 0) { int n = i(); int[] arr = input(n); shuffleAndSort(arr); long ans = 0; int cnt = 0; long sum = 0; for (int i = 1; i < n; i++) { ans += (long) cnt * arr[i] - sum; ans += arr[i]; cnt++; sum += arr[i]; } out.println(arr[n - 1] - ans); } out.flush(); } static void print(char A[]) { for (char c : A) { out.print(c); } out.println(); } static void print(boolean A[]) { for (boolean c : A) { out.print(c + " "); } out.println(); } static void print(int A[]) { for (int c : A) { out.print(c + " "); } out.println(); } static void print(long A[]) { for (long i : A) { out.print(i + " "); } out.println(); } static void print(List<Integer> A) { for (int a : A) { out.print(a + " "); } } static void printYes() { out.println("YES"); } static void printNo() { out.println("NO"); } static int i() { return in.nextInt(); } static long l() { return in.nextLong(); } static String s() { return in.nextLine(); } static int[][] inputWithIdx(int N) { int A[][] = new int[N][2]; for (int i = 0; i < N; i++) { A[i] = new int[]{i, in.nextInt()}; } return A; } static int[] input(int N) { int A[] = new int[N]; for (int i = 0; i < N; i++) { A[i] = in.nextInt(); } return A; } static long[] inputLong(int N) { long A[] = new long[N]; for (int i = 0; i < A.length; i++) { A[i] = in.nextLong(); } return A; } static int GCD(int a, int b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static long GCD(long a, long b) { if (b == 0) { return a; } else { return GCD(b, a % b); } } static void shuffleAndSort(int[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static void shuffleAndSort(long[] arr) { for (int i = 0; i < arr.length; i++) { int rand = (int) (Math.random() * arr.length); long temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } Arrays.sort(arr); } static boolean isPerfectSquare(double number) { double sqrt = Math.sqrt(number); return ((sqrt - Math.floor(sqrt)) == 0); } static void swap(int A[], int a, int b) { int t = A[a]; A[a] = A[b]; A[b] = t; } static long pow(long a, long b, int mod) { long pow = 1; long x = a; while (b != 0) { if ((b & 1) != 0) { pow = (pow * x) % mod; } x = (x * x) % mod; b /= 2; } return pow; } static long modInverse(long x, int mod) { return pow(x, mod - 2, mod); } static boolean isPrime(long N) { if (N <= 1) { return false; } if (N <= 3) { return true; } if (N % 2 == 0 || N % 3 == 0) { return false; } for (int i = 5; i * i <= N; i = i + 6) { if (N % i == 0 || N % (i + 2) == 0) { return false; } } return true; } } class Pair { int i, j; Pair(int i, int j) { this.i = i; this.j = j; } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
d2798f110707127f418e02fef36e3c54
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.TreeSet; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); CGreatGraphs solver = new CGreatGraphs(); solver.solve(1, in, out); out.close(); } static class CGreatGraphs { int n; int[] arr; public void readInput(Scanner sc) { n = sc.nextInt(); arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); } public void solve(int testNumber, Scanner sc, PrintWriter pw) { int tc = sc.nextInt(); while (tc-- > 0) { readInput(sc); shuffle(arr); Arrays.sort(arr); int idx = 0; long sum = 0; long ans = 0; for (int i = 0; i < n; i++) { while (idx < n && arr[idx] < arr[i]) { sum += arr[idx]; idx++; } ans += (-1L * arr[i] * idx) + sum; } TreeSet<Integer> set = new TreeSet<>(); set.add(0); for (int i = 1; i < n; i++) { Integer lower = set.floor(arr[i]); int diff = arr[i] - lower; ans += diff; set.add(arr[i]); } pw.println(ans); } } private void shuffle(int[] arr) { for (int i = 0; i < n; i++) { int rand = (int) (Math.random() * (i + 1)); int temp = arr[rand]; arr[rand] = arr[i]; arr[i] = temp; } } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() { try { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } catch (Exception e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
0b360a0d5cfb1f60b9f33f5063cf8489
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { //Scanner f = new Scanner(new File("uva.in")); //Scanner f = new Scanner(System.in); //BufferedReader f = new BufferedReader(new FileReader("uva.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int t = Integer.parseInt(f.readLine()); while(t-- > 0) { int n = Integer.parseInt(f.readLine()); StringTokenizer st = new StringTokenizer(f.readLine()); long[] d = new long[n]; for(int i = 0; i < n; i++) { d[i] = Integer.parseInt(st.nextToken()); } Arrays.sort(d); long subtract = 0; long sum = 0; for(int i = 0; i < n; i++) { subtract += d[i]*i-sum; sum += d[i]; } out.println(d[n-1]-subtract); } f.close(); out.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
8af67e525066693b191f74c63934f642
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Random; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; // Main -> CodeForcesProblemSet public final class Main { static FastReader fr = new FastReader(); static PrintWriter out = new PrintWriter(System.out); static final int gigamod = 1000000007; static int t = 1; static double epsilon = 0.00000001; static boolean[] isPrime; static int[] smallestFactorOf; @SuppressWarnings("unused") public static void main(String[] args) { t = fr.nextInt(); OUTER: for (int tc = 0; tc < t; tc++) { int n = fr.nextInt(); long[] arr = fr.nextLongArray(n); // Observations: // 1. The task is to determine the minimum sum of weights of roads that // matches the description. sort(arr); long answer = 0; long runninSum = arr[0]; for (int i = 1; i < n; i++) { answer += arr[i] - arr[i - 1]; answer -= (arr[i] * i - runninSum); runninSum += arr[i]; } out.println(answer); } out.close(); } static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) { if (smallestFactorOf == null) primeGenerator(15000000); HashMap<Integer, Integer> fnps = new HashMap<>(); while (num != 1) { fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1); num /= smallestFactorOf[num]; } return fnps; } static HashMap<Long, Integer> primeFactorization(long num) { // Returns map of factor and its power in the number. HashMap<Long, Integer> map = new HashMap<>(); while (num % 2 == 0) { num /= 2; Integer pwrCnt = map.get(2L); map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1); } for (long i = 3; i * i <= num; i += 2) { while (num % i == 0) { num /= i; Integer pwrCnt = map.get(i); map.put(i, pwrCnt != null ? pwrCnt + 1 : 1); } } // If the number is prime, we have to add it to the // map. if (num != 1) map.put(num, 1); return map; } static boolean[] primeGenerator(int upto) { // Sieve of Eratosthenes: isPrime = new boolean[upto + 1]; smallestFactorOf = new int[upto + 1]; Arrays.fill(smallestFactorOf, 1); Arrays.fill(isPrime, true); isPrime[1] = isPrime[0] = false; for (long i = 2; i < upto + 1; i++) if (isPrime[(int) i]) { smallestFactorOf[(int) i] = (int) i; // Mark all the multiples greater than or equal // to the square of i to be false. for (long j = i; j * i < upto + 1; j++) { if (isPrime[(int) j * (int) i]) { isPrime[(int) j * (int) i] = false; smallestFactorOf[(int) j * (int) i] = (int) i; } } } return isPrime; } static int KMPNumOcc(char[] text, char[] pat) { int n = text.length; int m = pat.length; char[] patPlusText = new char[n + m + 1]; for (int i = 0; i < m; i++) patPlusText[i] = pat[i]; patPlusText[m] = '^'; // Seperator for (int i = 0; i < n; i++) patPlusText[m + i] = text[i]; int[] fullPi = piCalcKMP(patPlusText); int answer = 0; for (int i = 0; i < n + m + 1; i++) if (fullPi[i] == m) answer++; return answer; } static int[] piCalcKMP(char[] s) { int n = s.length; int[] pi = new int[n]; for (int i = 1; i < n; i++) { int j = pi[i - 1]; while (j > 0 && s[i] != s[j]) j = pi[j - 1]; if (s[i] == s[j]) j++; pi[i] = j; } return pi; } @SuppressWarnings("serial") static class CountMap<T> extends TreeMap<T, Integer>{ CountMap() { } CountMap(T[] arr) { this.putCM(arr); } public Integer putCM(T key) { return super.put(key, super.getOrDefault(key, 0) + 1); } public Integer removeCM(T key) { int count = super.getOrDefault(key, -1); if (count == -1) return -1; if (count == 1) return super.remove(key); else return super.put(key, count - 1); } public Integer getCM(T key) { return super.getOrDefault(key, 0); } public void putCM(T[] arr) { for (T l : arr) this.putCM(l); } } static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) { // Returns the index of the last element // smaller than or equal to val. int idx = -1; while (lo <= hi) { int mid = lo + (hi - lo)/2; if (arr[mid] > val) { hi = mid - 1; } else { idx = mid; lo = mid + 1; } } return idx; } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static class Point implements Comparable<Point> { long right; long idx; long id; Point() { right = idx = id = 0; } Point(Point p) { this.right = p.right; this.idx = p.idx; this.id = p.id; } Point(long a, long b, long id) { this.right = a; this.idx = b; this.id = id; } Point(long a, long b) { this.right = a; this.idx = b; } @Override public int compareTo(Point o) { if (this.right < o.right) return -1; if (this.right > o.right) return 1; if (this.idx < o.idx) return -1; if (this.idx > o.idx) return 1; return 0; } public boolean equals(Point that) { return this.compareTo(that) == 0; } } static long[][] matExpo(long[][] mat, long power) { int n = mat.length; long[][] ans = new long[n][n]; if (power == 0) return null; if (power == 1) return mat; long[][] half = matExpo(mat, power / 2); ans = prod(half, half); if (power % 2 == 1) { ans = prod(ans, mat); } return ans; } static long[][] prod(long[][] mat1, long[][] mat2) { int n = mat1.length; long[][] prod = new long[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // determining prod[i][j] // it will be the dot product of mat1[i][] and mat2[][j] for (int k = 0; k < n; k++) prod[i][j] = (prod[i][j] + mat1[i][k] * mat2[k][j]) % gigamod; return prod; } static class FenwickTree { // NOTE: Never use 0-indexing. long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates public FenwickTree(int size) { array = new long[size + 1]; } public long rmq(int ind) { assert ind > 0; long max = 0; while (ind > 0) { max = Math.max(max, array[ind]); //Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number ind -= ind & (-ind); } return max; } public void update(int ind, long value) { assert ind > 0; while (ind < array.length) { array[ind] = Math.max(array[ind], value); //Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number ind += ind & (-ind); } } public int size() { return array.length - 1; } } static class UGraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public UGraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); adj[to].add(from); } public HashSet<Integer> adj(int from) { return adj[from]; } public int degree(int v) { return adj[v].size(); } public int V() { return adj.length; } public int E() { return E; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static void dfsMark(int current, boolean[] marked, UGraph g) { if (marked[current]) return; marked[current] = true; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, marked, g); } public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) { if (marked[current]) return; marked[current] = true; if (from != -1) distTo[current] = distTo[from] + 1; HashSet<Integer> adj = g.adj(current); int alreadyMarkedCtr = 0; for (int adjc : adj) { if (marked[adjc]) alreadyMarkedCtr++; dfsMark(adjc, current, distTo, marked, g, endPoints); } if (alreadyMarkedCtr == adj.size()) endPoints.add(current); } public static void bfsOrder(int current, UGraph g) { } public static void dfsMark(int current, int[] colorIds, int color, UGraph g) { if (colorIds[current] != -1) return; colorIds[current] = color; Iterable<Integer> adj = g.adj(current); for (int adjc : adj) dfsMark(adjc, colorIds, color, g); } public static int[] connectedComponents(UGraph g) { int n = g.V(); int[] componentId = new int[n]; Arrays.fill(componentId, -1); int colorCtr = 0; for (int i = 0; i < n; i++) { if (componentId[i] != -1) continue; dfsMark(i, componentId, colorCtr, g); colorCtr++; } return componentId; } public static boolean hasCycle(UGraph ug) { int n = ug.V(); boolean[] marked = new boolean[n]; boolean[] hasCycleFirst = new boolean[1]; for (int i = 0; i < n; i++) { if (marked[i]) continue; hcDfsMark(i, ug, marked, hasCycleFirst, -1); } return hasCycleFirst[0]; } // Helper for hasCycle. private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) { if (marked[current]) return; if (hasCycleFirst[0]) return; marked[current] = true; HashSet<Integer> adjc = ug.adj(current); for (int adj : adjc) { if (marked[adj] && adj != parent && parent != -1) { hasCycleFirst[0] = true; return; } hcDfsMark(adj, ug, marked, hasCycleFirst, current); } } } static class Digraph { // Adjacency list. private HashSet<Integer>[] adj; private static final String NEWLINE = "\n"; private int E; @SuppressWarnings("unchecked") public Digraph(int V) { adj = (HashSet<Integer>[]) new HashSet[V]; E = 0; for (int i = 0; i < V; i++) adj[i] = new HashSet<Integer>(); } public void addEdge(int from, int to) { if (adj[from].contains(to)) return; E++; adj[from].add(to); } public HashSet<Integer> adj(int from) { return adj[from]; } public int V() { return adj.length; } public int E() { return E; } public Digraph reversed() { Digraph dg = new Digraph(V()); for (int i = 0; i < V(); i++) for (int adjVert : adj(i)) dg.addEdge(adjVert, i); return dg; } public String toString() { StringBuilder s = new StringBuilder(); s.append(V() + " vertices, " + E() + " edges " + NEWLINE); for (int v = 0; v < V(); v++) { s.append(v + ": "); for (int w : adj[v]) { s.append(w + " "); } s.append(NEWLINE); } return s.toString(); } public static int[] KosarajuSharirSCC(Digraph dg) { int[] id = new int[dg.V()]; Digraph reversed = dg.reversed(); // Gotta perform topological sort on this one to get the stack. Stack<Integer> revStack = Digraph.topologicalSort(reversed); // Initializing id and idCtr. id = new int[dg.V()]; int idCtr = -1; // Creating a 'marked' array. boolean[] marked = new boolean[dg.V()]; while (!revStack.isEmpty()) { int vertex = revStack.pop(); if (!marked[vertex]) sccDFS(dg, vertex, marked, ++idCtr, id); } return id; } private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) { marked[source] = true; id[source] = idCtr; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id); } public static Stack<Integer> topologicalSort(Digraph dg) { // dg has to be a directed acyclic graph. // We'll have to run dfs on the digraph and push the deepest nodes on stack first. // We'll need a Stack<Integer> and a int[] marked. Stack<Integer> topologicalStack = new Stack<Integer>(); boolean[] marked = new boolean[dg.V()]; // Calling dfs for (int i = 0; i < dg.V(); i++) if (!marked[i]) runDfs(dg, topologicalStack, marked, i); return topologicalStack; } static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) { marked[source] = true; for (Integer adjVertex : dg.adj(source)) if (!marked[adjVertex]) runDfs(dg, topologicalStack, marked, adjVertex); topologicalStack.add(source); } } static int mapTo1D(int row, int col, int n, int m) { // Maps elements in a 2D matrix serially to elements in // a 1D array. return row * m + col; } static int[] mapTo2D(int idx, int n, int m) { // Inverse of what the one above does. int[] rnc = new int[2]; rnc[0] = idx / m; rnc[1] = idx % m; return rnc; } static class FastReader { private BufferedReader bfr; private StringTokenizer st; public FastReader() { bfr = new BufferedReader(new InputStreamReader(System.in)); } String next() { if (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(bfr.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()); } char nextChar() { return next().toCharArray()[0]; } String nextString() { return next(); } int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = nextInt(); return arr; } double[] nextDoubleArray(int n) { double[] arr = new double[n]; for (int i = 0; i < arr.length; i++) arr[i] = nextDouble(); return arr; } long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) arr[i] = nextLong(); return arr; } int[][] nextIntGrid(int n, int m) { int[][] grid = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } long[][] nextLongGrid(int n, int m) { long[][] grid = new long[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) grid[i][j] = fr.nextInt(); } return grid; } } static String toString(int[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(boolean[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(long[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + " "); return sb.toString(); } static String toString(char[] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) sb.append(dp[i] + ""); return sb.toString(); } static String toString(int[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(long[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(double[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + " "); } sb.append('\n'); } return sb.toString(); } static String toString(char[][] dp) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < dp.length; i++) { for (int j = 0; j < dp[i].length; j++) { sb.append(dp[i][j] + ""); } sb.append('\n'); } return sb.toString(); } } // NOTES: // ASCII VALUE OF 'A': 65 // ASCII VALUE OF 'a': 97 // Range of long: 9 * 10^18 // ASCII VALUE OF '0': 48 // Primes upto 'n' can be given by (n / (logn)).
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
1b1484b58688d3668a3ac9c5fe599c56
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import static java.lang.System.out; public class Round728Div2C { public static void main(String[] args) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int T = Integer.parseInt(st.nextToken()); StringBuilder sb = new StringBuilder(); while(T-->0) { st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); int[] arr = readArr(N, infile, st); if(N == 1) { sb.append("0\n"); continue; } Arrays.sort(arr); long[] diffs = new long[N-1]; for(int i=0; i < N-1; i++) diffs[i] = arr[i+1]-arr[i]; long res = 0L; for(int i=0; i < N-1; i++) res -= diffs[i]*(i+1)*(N-1-i); //System.out.println("! "+diffs[0]); for(long x: diffs) res += x; sb.append(res+"\n"); } out.println(sb); //BufferedReader infile = new BufferedReader(new FileReader("input.txt")); //System.setOut(new PrintStream(new File("output.txt"))); } 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; } public static void print(int[] arr) { //for debugging only for(int x: arr) out.print(x+" "); out.println(); } public static long[] readArr2(int N, BufferedReader infile, StringTokenizer st) throws Exception { long[] arr = new long[N]; st = new StringTokenizer(infile.readLine()); for(int i=0; i < N; i++) arr[i] = Long.parseLong(st.nextToken()); return arr; } public static boolean isPrime(long n) { if(n < 2) return false; if(n == 2 || n == 3) return true; if(n%2 == 0 || n%3 == 0) return false; long sqrtN = (long)Math.sqrt(n)+1; for(long i = 6L; i <= sqrtN; i += 6) { if(n%(i-1) == 0 || n%(i+1) == 0) return false; } return true; } public static long gcd(long a, long b) { if(a > b) a = (a+b)-(b=a); if(a == 0L) return b; return gcd(b%a, a); } public static int lcm(int a, int b) { return (a * b) / lcm(a, b); } public static String sort(String s){ char[] c = s.toCharArray(); Arrays.sort(c); return new String(c); } static String deleteIth(String str, int i) { str = str.substring(0, i) + str.substring(i + 1); return str; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
866302655a621f2fdaee906cde8d57c7
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Scanner; import java.util.StringTokenizer; public class Main { static AReader scan = new AReader(); static Scanner scan2 = new Scanner(System.in); static int N = 100010; static void slove() { int n = scan.nextInt(); int[] d = new int[n+1]; for(int i=1;i<=n;i++) d[i] = scan.nextInt(); Arrays.sort(d); long res = 0; long ans = 0; for(int i=1;i<=n;i++){ long ss = (long)(i-1) * d[i] - res; ans += ss; res +=d[i]; } ans -=d[n]; ans *=-1; System.out.println(ans); } public static void main(String[] args) { int t = scan.nextInt(); while (t-- > 0) { slove(); } } } class AReader { private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); private StringTokenizer tokenizer = new StringTokenizer(""); private String innerNextLine() { try { return reader.readLine(); } catch (IOException ex) { return null; } } public boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String nextLine = innerNextLine(); if (nextLine == null) { return false; } tokenizer = new StringTokenizer(nextLine); } return true; } public String nextLine() { tokenizer = new StringTokenizer(""); return innerNextLine(); } public String next() { hasNext(); return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } class Node{ int x; int y; public Node(int x, int y) { this.x = x; this.y = y; } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
89c50d996fd346b6ad0e44de0ac76128
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; import java.io.IOException; import java.util.Random; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); COtlichnieGrafi solver = new COtlichnieGrafi(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class COtlichnieGrafi { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = in.nextInt(); } ArrayUtils.sort(a); long prev = 0; long ans = 0; for (int i = 1; i < n; i++) { prev -= i * (a[i] - a[i - 1]); ans += prev + (a[i] - a[i - 1]); } out.println(ans); } } static class ArrayUtils { static final long seed = System.nanoTime(); static final Random rand = new Random(seed); public static void sort(long[] a) { shuffle(a); Arrays.sort(a); } public static void shuffle(long[] a) { for (int i = 0; i < a.length; i++) { int j = rand.nextInt(i + 1); long t = a[i]; a[i] = a[j]; a[j] = t; } } } 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
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
817158c24580ba00ce4fec3ca7653ee1
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
// "static void main" must be defined in a public class. import java.util.*; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int t=sc.nextInt(); while(t-->0){ int n=sc.nextInt(); long[]arr=new long[n]; for(int i=0;i<n;i++){ arr[i]=sc.nextLong(); } Arrays.sort(arr); long[]pre=new long[n]; pre[0]=arr[0]; for(int i=1;i<n;i++){ pre[i]=arr[i]+pre[i-1]; } long sum=0; int i=n-1; while(i>=2){ sum=sum-arr[i]*(i-1)+pre[i-2]; i--; } System.out.println(sum); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
aad86e9298f59724a7d4b7fac3133930
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; public class Oliver_And_The_Game { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); long[] arr = new long[n]; String[] parts = br.readLine().split(" "); for (int i = 0; i < n; i++) { arr[i] = Integer.parseInt(parts[i]); } Arrays.sort(arr); long sum = arr[n - 1]; long[] neg = new long[n]; neg[0] = 0; for(int i = 1; i < n ; i++) { neg[i] = neg[i - 1] + i * (arr[i] - arr[i - 1]); sum -= neg[i]; } System.out.println(sum); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
b91976ff44e2ceddd3b0c1462a970694
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package codeforces.round728div2; import java.io.*; import java.util.*; //Think through the entire logic before jump into coding! //Be aware of integer overflow! public class C { static InputReader in; static PrintWriter out; public static void main(String[] args) { //initReaderPrinter(true); initReaderPrinter(false); solve(in.nextInt()); //solve(1); } static void solve(int testCnt) { for (int testNumber = 0; testNumber < testCnt; testNumber++) { int n = in.nextInt(); Integer[] d = in.nextIntArray(n); Arrays.sort(d); long[] w = new long[n - 1]; for(int i = 0; i < n - 1; i++) { w[i] = d[i + 1] - d[i]; } long currSum = 0; for(int i = n - 2; i >= 0; i--) { currSum += w[i] * (i + 1); } long ans = d[n - 1] - currSum; for(int i = n - 3; i >= 0; i--) { currSum -= w[i + 1] * (i + 2); ans -= currSum; } out.println(ans); } out.close(); } static void initReaderPrinter(boolean test) { if (test) { try { in = new InputReader(new FileInputStream("src/input.in")); out = new PrintWriter(new FileOutputStream("src/output.out")); } catch (IOException e) { e.printStackTrace(); } } else { in = new InputReader(System.in); out = new PrintWriter(System.out); } } static class InputReader { BufferedReader br; StringTokenizer st; InputReader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream), 32768); } catch (Exception e) { e.printStackTrace(); } } String next() { while (st == null || !st.hasMoreTokens()) { 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; } Integer[] nextIntArray(int n) { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } int[] nextIntArrayPrimitive(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } Long[] nextLongArray(int n) { Long[] a = new Long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } long[] nextLongArrayPrimitive(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
32c9d404bb9517216298dcb4327e31ff
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Pranay2516 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastReader in = new FastReader(inputStream); PrintWriter out = new PrintWriter(outputStream); CGreatGraphs solver = new CGreatGraphs(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class CGreatGraphs { public void solve(int testNumber, FastReader in, PrintWriter out) { int n = in.nextInt(); long[] d = in.readLongArray(n); func.sort(d); long ans = 0; long count = 0; for (int i = 2; i < n; i++) { ans -= d[i] * (i - 1); count += d[i - 2]; ans += count; } out.println(ans); } } static class FastReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastReader.SpaceCharFilter filter; public FastReader(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 String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public long[] readLongArray(int size) { long[] array = new long[size]; for (int i = 0; i < size; i++) array[i] = nextLong(); return array; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } static class func { public static void sort(long[] arr) { //Taken from @KharYusuf int n = arr.length, mid, h, s, l, i, j, k; long[] res = new long[n]; n--; for (s = 1; s <= n; s <<= 1) { for (l = 0; l < n; l += (s << 1)) { h = Math.min(l + (s << 1) - 1, n); mid = Math.min(l + s - 1, n); i = l; j = mid + 1; k = l; while (i <= mid && j <= h) res[k++] = (arr[i] <= arr[j] ? arr[i++] : arr[j++]); while (i <= mid) res[k++] = arr[i++]; while (j <= h) res[k++] = arr[j++]; for (k = l; k <= h; k++) arr[k] = res[k]; } } } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
454920b33a152aff5813a06d9d01093f
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import javafx.util.Pair; public class Main { static void sort(long a[]) { Random ran = new Random(); for (int i = 0; i < a.length; i++) { int r = ran.nextInt(a.length); long temp = a[r]; a[r] = a[i]; a[i] = temp; } Arrays.sort(a); } public static void main(String[] args) { FastScanner input = new FastScanner(); int tc = input.nextInt(); while (tc-- > 0) { int n = input.nextInt(); long a[] = new long[n]; for (int i = 0; i < n; i++) { a[i] = input.nextLong(); } sort(a); long ans = a[n-1]; long neg[] = new long[n]; for (int i = 1; i <n; i++) { neg[i]=(neg[i-1]+i*(a[i]-a[i-1])); ans-=neg[i]; } System.out.println(ans); } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
39356438b47b5580498eca59bbf6d1fe
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.util.*; import java.math.*; public class GreatGraphs { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int runs = sc.nextInt(); while(runs-->0) { int size = sc.nextInt(); long[] arr = new long[size]; for(int i = 0;i<size;i++) arr[i] = sc.nextLong(); if(size==1||size==2) { System.out.println("0"); continue; } Arrays.sort(arr); int maxDex = 0; long out = 0; for(int i = 1;i<size;i++) { out+=arr[i]-arr[i-1]; } long temp = 0; for(int i = 1;i<size;i++) { long hold = arr[i-1]-arr[i]; hold*=i; hold+=temp; out+=hold; temp = hold; } System.out.println(out); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
afcebc399f9cc7d0877d3e8556234205
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
//package com.cf.div2.c728; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C { static PrintWriter out = new PrintWriter(System.out); static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) {} return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } } public static void main(String[] args) { FastScanner sc = new FastScanner(); int t = sc.nextInt(); while (t-- > 0) { int n = sc.nextInt(); long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextLong(); } Arrays.sort(arr); long sum = arr[n - 1]; long neg = 0; for (int i = 1; i < n; i++) { neg += (arr[i] - arr[i - 1]) * i; sum -= neg; } out.println(sum); } out.close(); } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
0bf8b04f3846e7bd2292fb571eaaa7a8
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; public class GreatGraphs { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int t = Integer.parseInt(br.readLine()); while (t-- > 0) { int n = Integer.parseInt(br.readLine()); String s[] = br.readLine().split(" "); long a[]= new long[n]; for(int i = 0; i < n; i++) { a[i] = Long.parseLong(s[i]); } Arrays.sort(a); long[] diffs = new long[n-1]; for(int i=0; i < n-1; i++) diffs[i] = a[i+1]-a[i]; long res = 0L; for(int i=0; i < n-1; i++) res -= diffs[i]*(i+1)*(n-1-i); //System.out.println("! "+diffs[0]); for(long x: diffs) res += x; System.out.println(res); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output
PASSED
fb5b910c3e84da45818d27009428563f
train_107.jsonl
1624635300
Farmer John has a farm that consists of $$$n$$$ pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is impossible for the cows to get stuck in a time loop, where they can infinitely go back in time by traveling across a sequence of roads. Also, each pair of pastures is connected by at most one road in each direction.Unfortunately, Farmer John lost the map of the farm. All he remembers is an array $$$d$$$, where $$$d_i$$$ is the smallest amount of time it took the cows to reach the $$$i$$$-th pasture from pasture $$$1$$$ using a sequence of roads. The cost of his farm is the sum of the weights of each of the roads, and Farmer John needs to know the minimal cost of a farm that is consistent with his memory.
256 megabytes
import java.io.*; import java.util.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } static int readInt() throws IOException { return Integer.parseInt(next()); } static long readLong() throws IOException { return Long.parseLong(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readChar() throws IOException { return next().charAt(0); } static String readLine() throws IOException { return br.readLine(); } static class Pair implements Comparable<Pair> { int f, s; Pair(int f, int s) { this.f = f; this.s = s; } public int compareTo(Pair other) { if (this.f != other.f) return this.f - other.f; return this.s - other.s; } } public static void main(String[] args) throws IOException { for (int t = readInt(); t > 0; --t) { int n = readInt(); long d[] = new long[n + 1]; for (int i = 1; i <= n; ++i) d[i] = readInt(); Arrays.sort(d, 1, n + 1); long ans = 0, sum = d[1]; for (int i = 2; i <= n; ++i) { if (d[i] > 0) ans += d[i] - d[i - 1]; ans += sum - d[i]*(i - 1); sum += d[i]; } System.out.println(ans); } } }
Java
["3\n3\n0 2 3\n2\n0 1000000000\n1\n0"]
2 seconds
["-3\n0\n0"]
NoteIn the first test case, you can add roads from pasture $$$1$$$ to pasture $$$2$$$ with a time of $$$2$$$, from pasture $$$2$$$ to pasture $$$3$$$ with a time of $$$1$$$, from pasture $$$3$$$ to pasture $$$1$$$ with a time of $$$-3$$$, from pasture $$$3$$$ to pasture $$$2$$$ with a time of $$$-1$$$, from pasture $$$2$$$ to pasture $$$1$$$ with a time of $$$-2$$$. The total cost is $$$2 + 1 + -3 + -1 + -2 = -3$$$.In the second test case, you can add a road from pasture $$$1$$$ to pasture $$$2$$$ with cost $$$1000000000$$$ and a road from pasture $$$2$$$ to pasture $$$1$$$ with cost $$$-1000000000$$$. The total cost is $$$1000000000 + -1000000000 = 0$$$.In the third test case, you can't add any roads. The total cost is $$$0$$$.
Java 8
standard input
[ "constructive algorithms", "graphs", "greedy", "shortest paths", "sortings" ]
7dfe0db5a99e6e4d71eb012fab07685b
The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the number of pastures. The second line of each test case contains $$$n$$$ space separated integers $$$d_1, d_2, \ldots, d_n$$$ ($$$0 \leq d_i \leq 10^9$$$) — the array $$$d$$$. It is guaranteed that $$$d_1 = 0$$$. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.
1,400
For each test case, output the minimum possible cost of a farm that is consistent with Farmer John's memory.
standard output