[Question]
  [
# The Challenge
There are N cities aligned in a straight line. The i-th city is located `A[i]` kilometers to the right of the origin. No two cities will be in the same place.
You are going to build an electrical grid with some power plants. Power plants must be built inside a city. However, you are only allowed to build `K` (< N) power plants, so there will be some cities with no power plants in them. For each city with no power plants, you must build a cable between it and **the nearest city that has a power plant**.
For example, if there are three cities located at `0, 1, 2`, and only the city at `0` has a power plant, you need to build two cables, one from `2` to `0`(2km) and the other from `1` to `0`(1km), which have a total length of 3km.
Given `K` and positions of cities (`A`), you should compute the minimum kilometers of cable you need to build the grid. 
# Example Testcases
```
K = 1, A = [0, 2, 4, 6, 8] : 12 
# build power plant in the city at position 4, total length = 4 + 2 + 0 + 2 + 4 = 12
K = 3, A = [0, 1, 10, 11, 20, 21, 22, 30, 32] : 23
# build power plants in cities at positions 0, 10 and 22
K = 5, A = [0, 1, 3, 6, 8, 11, 14] : 3
# build power plants in all cities except those at positions 0, 3
K = 6, A = [0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84] : 49
```
# Specifications
* You should implement a function or a program, which takes a positive integer `K` and a list of integers `A` in any form, and output/return an integer representing the answer.
* `A` is sorted in ascending order, and all elements are non-negative integers.
* `A[0] = 0`, and `A[N-1]` will be no more than 1000N.
* Note that the output will be in magnitude of 1000N2, so in larger cases, you may need 64-bit integers in some languages.
* Multithreading is **not** allowed (I will set the affinity of your program to only 1 core when judging). Compiler optimizations (such as `-O2` in C) are allowed.
# Scoring
* I will time your code on my computer (Ubuntu 16.04 with Intel i7-3770S processor) with different size of testcases. Specifically, I will generate some testcases with N = floor(2x/5) where x is a positive integer.  
Your score will be the x value of the smallest testcase that your program uses more than 10 seconds or 1 GiB of memory, or doesn't give a correct answer.
	+ The answer with highest score wins. If two answers get the same score, the earlier answer wins.
* All programs will be judged by the same set of testcases.
* Feel free to post your own scorings. Explanations of your algorithm are encouraged.
# Bonus
[This](https://tio.run/##lVZbr9pGEH7Gv2KaKsg@NpRL1arc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TO6UKhLnRb551AV4dfZLC9ebY7kXMKjYf6UgzsZ6lQ4A3hwGCTscR79T@4HbHQpAwYtouLyrOIVRWnCtw/TDnTonEgbT0JVjP8DUSVhMXoYFpe8tjkkHAtyVAVpLkUnfEwLoLz9QVNrhN02xmNMkxFN8Jzg/wRNJ3@FiQqO1W3w5/Q2QIjL0HXHv/4N) is my C++ program, it scores **108**. You can verify the SHA-256 digest `9a87fa183bad1e3a83d2df326682598796a216b3a4262c32f71dfb06df12935d` by the whole code segment (without footer) in the link.
The algorithm combines binary search and Knuth's optimization to find the correct penalty of each plant to get the desired number. The complexity is O(N log N log A[N-1]). I was surprised that the program got a higher score than the [O(N log A[N−1]) solution by Anders Kaseorg](https://codegolf.stackexchange.com/a/149780/75905). It's probably due to the fact that the log case in Knuth's optimization won't usually occur.
Note that this challenge is the same as [IOI 2000 Post Office](http://www.ioinformatics.org/locations/ioi00/contest/day2/post/post.pdf). The original constraints are N <= 300 and K <= 30, though.
  
[Answer]
# [Rust](https://www.rust-lang.org/), score = 104
This is an implementation of the algorithm noted by [Grønlund et al. (2017)](https://arxiv.org/abs/1701.07204) at the end of §3.3.1, though I had to follow a long citation chain and fill in some missing details. It runs in *O*(*N* log *A*[*N* − 1]) time.
Compile with `rustc -O`. Input format is `K` on the first line, followed by the entries of `A`, one entry per line, all on stdin.
(Note: I’m submitting this an hour after the bounty deadline, but I expect the [last version I submitted before the bounty deadline](https://codegolf.stackexchange.com/revisions/149780/16), which ran in *O*(*N* log *N* log *A*[*N* − 1]) time, to score about 94.)
```
use std::cmp::min;
use std::io::{self, BufRead};
use std::iter::{once, Cloned};
use std::num::Wrapping;
use std::ops::Range;
use std::slice;
use std::time::Instant;
use std::u64;
type Cost = u64;
const INF: Cost = u64::MAX;
trait ColsTrait<Col>: Clone {
    type Iter: Iterator<Item = Col>;
    fn len(&self) -> usize;
    fn iter(&self) -> Self::Iter;
    fn slice(&self, range: Range<usize>) -> Self;
}
impl<'a, Col: Clone> ColsTrait<Col> for &'a [Col] {
    type Iter = Cloned<slice::Iter<'a, Col>>;
    fn len(&self) -> usize {
        (*self).len()
    }
    fn iter(&self) -> Self::Iter {
        (*self).iter().cloned()
    }
    fn slice(&self, range: Range<usize>) -> Self {
        unsafe { self.get_unchecked(range) }
    }
}
impl ColsTrait<usize> for Range<usize> {
    type Iter = Range<usize>;
    fn len(&self) -> usize {
        self.end - self.start
    }
    fn iter(&self) -> Range<usize> {
        self.clone()
    }
    fn slice(&self, range: Range<usize>) -> Self {
        Range {
            start: self.start + range.start,
            end: self.start + range.end,
        }
    }
}
fn smawk<Col: Copy, Cols: ColsTrait<Col>, Key: Ord, F: Copy + Fn(usize, Col) -> Key>(
    n: usize,
    shift: u32,
    cols: Cols,
    f: F,
) -> Vec<usize> {
    if n == 0 {
        Vec::new()
    } else if cols.len() > n {
        let mut s = Vec::with_capacity(n);
        let mut sk = Vec::with_capacity(n);
        for (jk, j) in cols.iter().enumerate() {
            while match s.last() {
                Some(&l) => f(!(!(s.len() - 1) << shift), j) <= f(!(!(s.len() - 1) << shift), l),
                None => false,
            } {
                s.pop();
                sk.pop();
            }
            if s.len() < n {
                s.push(j);
                sk.push(jk);
            }
        }
        smawk1(
            n,
            shift,
            cols,
            f,
            smawk(n / 2, shift + 1, &s[..], f)
                .into_iter()
                .map(|h| unsafe { *sk.get_unchecked(h) }),
        )
    } else {
        smawk1(
            n,
            shift,
            cols.clone(),
            f,
            smawk(n / 2, shift + 1, cols, f).into_iter(),
        )
    }
}
fn smawk1<
    Col: Copy,
    Cols: ColsTrait<Col>,
    Key: Ord,
    F: Fn(usize, Col) -> Key,
    Iter: Iterator<Item = usize>,
>(
    n: usize,
    shift: u32,
    cols: Cols,
    f: F,
    iter: Iter,
) -> Vec<usize> {
    let mut out = Vec::with_capacity(n);
    let mut range = 0..0;
    for (i, k) in iter.enumerate() {
        range.end = k + 1;
        out.push(
            range
                .clone()
                .zip(cols.slice(range.clone()).iter())
                .min_by_key(|&(_, col)| f(!(!(2 * i) << shift), col))
                .unwrap()
                .0,
        );
        out.push(k);
        range.start = k;
    }
    if n % 2 == 1 {
        range.end = cols.len();
        out.push(
            range
                .clone()
                .zip(cols.slice(range.clone()).iter())
                .min_by_key(|&(_, col)| f(!(!(n - 1) << shift), col))
                .unwrap()
                .0,
        );
    }
    out
}
fn solve(k: usize, a: &[Cost]) -> Cost {
    if k >= a.len() {
        return 0;
    }
    let sa = once(Wrapping(0))
        .chain(a.iter().scan(Wrapping(0), |s, &x| {
            *s += Wrapping(x);
            Some(*s)
        }))
        .collect::<Vec<_>>();
    let c = |i: usize, j: usize| {
        let h = (i - j) / 2;
        unsafe {
            (sa.get_unchecked(i) - sa.get_unchecked(i - h) - sa.get_unchecked(j + h)
                + sa.get_unchecked(j))
                .0
        }
    };
    let cost1 = c(a.len(), 0);
    if k == 1 {
        return cost1;
    }
    let cost2 = (1..a.len()).map(|j| c(j, 0) + c(a.len(), j)).min().unwrap();
    let mut low = 0;
    let mut high = cost1 - cost2;
    let mut ret = INF;
    while low <= high {
        let penalty = low + (high - low) / 2;
        let mut out = vec![(INF, 0); a.len() + 1];
        out[0] = (0, 0);
        let mut begin = 0;
        let mut chunk = 1;
        loop {
            let r = min(a.len() + 1 - begin, 2 * chunk);
            let edge = begin + chunk;
            let (out0, out1) = out.split_at_mut(edge);
            let f = |i: usize, j: usize| {
                let h = (edge + i - j) / 2;
                let &(cost, count) = unsafe { out0.get_unchecked(j) };
                (
                    cost.saturating_add(
                        unsafe {
                            sa.get_unchecked(edge + i) - sa.get_unchecked(edge + i - h)
                                - sa.get_unchecked(j + h)
                                + sa.get_unchecked(j)
                        }.0 + penalty,
                    ),
                    count + 1,
                )
            };
            for ((i, j), o) in smawk(r - chunk, 0, begin..edge, &f)
                .into_iter()
                .enumerate()
                .zip(out1.iter_mut())
            {
                *o = min(f(i, begin + j), *o);
            }
            let x = unsafe { out1.get_unchecked(r - 1 - chunk) };
            if let Some(j) = (edge..begin + r - 1).find(|&j| &f(r - 1 - chunk, j) <= x) {
                begin = j;
                chunk = 1;
            } else if r == a.len() + 1 - begin {
                break;
            } else {
                chunk *= 2;
            }
        }
        let &(cost, count) = unsafe { out.get_unchecked(a.len()) };
        if count > k {
            low = penalty + 1;
        } else {
            ret = cost.wrapping_sub(k as Cost * penalty);
            if count == k {
                return ret;
            }
            high = penalty - 1;
        }
    }
    ret
}
fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let k = lines.next().unwrap().unwrap().parse().unwrap();
    let a = lines
        .map(|s| s.unwrap().parse().unwrap())
        .collect::<Vec<_>>();
    let start = Instant::now();
    let cost = solve(k, &a);
    let time = start.elapsed();
    println!(
        "cost: {}\ntime: {}.{:09} sec",
        cost,
        time.as_secs(),
        time.subsec_nanos()
    );
}
```
[Try it online!](https://tio.run/##1Vhtb9s2EP7uX3EtsFRyFM3OimJTbANbgQLFsBZoh21AFhisTMeyZUowpTpp7L@@7O4oydSLk2zrl7lAKvGOx3t97qhNrrP7@1xL0NksCMJ1GgTrSF30qqUoCYI7LeO5Bz/l8w9SzPY2NZMbpCcqlB68jhMla2SVr4Pg941I00hdW@tJqoPgg1DX0lrUcRTa71m0lkHwVulMqMxaz1@9vOj1sttUwutEZzAGXgkT5IS3794E1nIQ/PLjH8S9EVGG67H@lZ5G@DQJjMJw1wP8sby3ZA7/FVmyGeHDGuUQ8wUzzRXEUjkn5A8XziaQ6@iLrGjkDYv4ER/QAFysONhGw@LBhhwQAPthxJIm1b6L3r7Xi9ZpPHohPNKg0HbSMALmyQZOXgi4xLerpi2kPAdlxAcbZUqJkweNKkTRz@kzyScul1f3j1rcsZ15XT9khZqCnuwYS3CutJijokC7/GuZTXMVLmS4QvEswi3k70tnWs4zYtl99jkdHrTJT/QYKyTVDM7MI6bwJnvQcx06VILYY1/DYUy33vkEUi2w1IRTI868eTVmNKmTFdcPjJbPSc@12K5GJoGT9JYzTweNLPbgZ3kbwPvNzIM3hhFlv1EO28J72B7kmjgsXgXG6eZYvYjmaET@3bl5D6szz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nBq2NpeDVqD6@BfRaMyAqdM4yqYim6KiDknpED5/vJhaRcUKnUJXbdm8Jw7FnfAwVxnpVI1apGqrJsqMr1Vla8WMChqNE5jlIkNsmYrZrJvxaLW3JtxmiZYmdla6ZX9HwTd/T4eKJ0HH0V17f4A7ikLxOtlc74g/MUA8VbbI9eMaEeKZiYamJeJEwoOTmVY3VPOUplhOnklc3yevYaP4x4O6NYZ1d3RKee5OnOcNbG3HvZ8UhTgn1cuqIhP6yYNXKMrpm0YaD5vfVWgaKK1vpTSiNQnh3rd0y1Ly/VIJ3u3680jNcNJARD6Z1yWWd82brgtriVLLdh11oFT94r6hJtKBTF3HbKRYdcq5O3Juf9yEiK6L46OQ0XB12b5sJ/MnCErmCbbFBgRznyr7SG1u71TfNCiGmm0xxEx1/slZgdBm4OqX0txWlI0S43FLC6s/438PZVvRQkuFz2oKW10dxRRD4prmNNe6EulsxglB36j5udW7IyXpiwwT/TgJV9jmedHmpMThRV/Jm8waBA4Pqdho2TkiiHJzr37z1jvQx/c/dRQs7xjFV/AgUMm2NiqaL93F@IzoIywifUBn41GGL2ORavruaujpBjEpVs8OfeU5yQrgbv@n4i/v@OTfBYMf9qBl@PyAnJzA1Rux@kJPkUfb93Nex3TC9akSKtEFuOHx@/v7YW/QO@@97L3qff9XOI/Ftb4/e/83 "Rust – Try It Online")
# [Rust](https://www.rust-lang.org/), pretest score = 73
Compile with `rustc -O`. Input format is `K` on the first line, followed by the entries of `A`, one entry per line, all on stdin.
```
use std::io::{self, BufRead};
use std::iter::once;
use std::num::Wrapping;
use std::time::Instant;
use std::u64;
type Cost = u64;
const INF: Cost = u64::MAX;
fn smawk<Col: Clone, Key: Ord, F: Clone + Fn(usize, &Col) -> Key>(
    n: usize,
    shift: u32,
    cols: &[Col],
    f: F,
) -> Vec<usize> {
    if n == 0 {
        Vec::new()
    } else if cols.len() > n {
        let mut s = Vec::with_capacity(n);
        let mut sk = Vec::with_capacity(n);
        for (jk, j) in cols.iter().enumerate() {
            while match s.last() {
                Some(l) => f(!(!(s.len() - 1) << shift), j) <= f(!(!(s.len() - 1) << shift), l),
                None => false,
            } {
                s.pop();
                sk.pop();
            }
            if s.len() < n {
                s.push(j.clone());
                sk.push(jk);
            }
        }
        smawk1(
            n,
            shift,
            cols,
            f.clone(),
            smawk(n / 2, shift + 1, &s, f)
                .into_iter()
                .map(|h| unsafe { *sk.get_unchecked(h) }),
        )
    } else {
        smawk1(
            n,
            shift,
            cols,
            f.clone(),
            smawk(n / 2, shift + 1, &cols, f).into_iter(),
        )
    }
}
fn smawk1<Col: Clone, Key: Ord, F: Clone + Fn(usize, &Col) -> Key, Iter: Iterator<Item = usize>>(
    n: usize,
    shift: u32,
    cols: &[Col],
    f: F,
    iter: Iter,
) -> Vec<usize> {
    let mut out = Vec::with_capacity(n);
    let mut range = 0..0;
    for (i, k) in iter.enumerate() {
        range.end = k + 1;
        out.push(
            range
                .clone()
                .zip(unsafe { cols.get_unchecked(range.clone()) })
                .min_by_key(|&(_, col)| f(!(!(2 * i) << shift), col))
                .unwrap()
                .0,
        );
        out.push(k);
        range.start = k;
    }
    if n % 2 == 1 {
        range.end = cols.len();
        out.push(
            range
                .clone()
                .zip(unsafe { cols.get_unchecked(range.clone()) })
                .min_by_key(|&(_, col)| f(!(!(n - 1) << shift), col))
                .unwrap()
                .0,
        );
    }
    out
}
fn solve(k: usize, a: &[Cost]) -> Cost {
    let mut cost = vec![INF; a.len() + 1 - k];
    let sa = once(Wrapping(0))
        .chain(a.iter().scan(Wrapping(0), |s, &x| {
            *s += Wrapping(x);
            Some(*s)
        }))
        .collect::<Vec<_>>();
    cost[0] = 0;
    let cols = (0..a.len() + 1 - k).collect::<Vec<_>>();
    for m in 0..k {
        cost = {
            let f = |i: usize, &j: &usize| {
                if i + 1 >= j {
                    let h = (i + 1 - j) / 2;
                    unsafe {
                        cost.get_unchecked(j).saturating_add(
                            (sa.get_unchecked(i + m + 1) - sa.get_unchecked(i + m + 1 - h)
                                - sa.get_unchecked(j + m + h)
                                + sa.get_unchecked(j + m))
                                .0,
                        )
                    }
                } else {
                    INF
                }
            };
            smawk(a.len() + 1 - k, 0, &cols, &f)
                .into_iter()
                .enumerate()
                .map(|(i, j)| f(i, &j))
                .collect()
        };
    }
    cost[a.len() - k]
}
fn main() {
    let stdin = io::stdin();
    let mut lines = stdin.lock().lines();
    let k = lines.next().unwrap().unwrap().parse().unwrap();
    let a = lines
        .map(|s| s.unwrap().parse().unwrap())
        .collect::<Vec<_>>();
    let start = Instant::now();
    let cost = solve(k, &a);
    let time = start.elapsed();
    println!(
        "cost: {}\ntime: {}.{:09} sec",
        cost,
        time.as_secs(),
        time.subsec_nanos()
    );
}
```
[Try it online!](https://tio.run/##1Vd7a@NGEP9fn2JyULNKFNVOj6OVH9AeBMLRO2ihLaTB7MmrSJa0Mt7VOTlbX73p7EqyVpaUXB9QugYjzWtndmZ@s9rmQj495YKBkCvPizLP2wuWBA78kAc/MboqplbDlWzreRn3mUHkeep5v27pZhPxe4Muo5R53g0XknJp0PM3r6eWJR83DN5mQsIcNMXPUBJu3l97Btnzfvz@N5QOOIiU7uLZ2yxBfpJx5sA79ujBh@3KgeuKBhdwzUkuos/IHqGsDZcLJbcgFuDiHpRM/SbCKJBI@eaqfPezRHgwukW9u5ISeHDtWNrIL8yfad0F7DUvCoDDfA7j6l0tFMLzYDtia1IBLMGoUVKZdhPGiQ0LVGs0EiYhzSUIjFdr7yIZLn26oX4kHwm3p13R@GXZINsCWccOrG2IeLm9Sh6xXYb5YlsqGfrS@KHWLowSBimVfgjoLRWyI6LWz1nKCJ7sfAEBOcNfHdklTGyYzcpztfXes/kLMontdDZ4rzKprFM8vTa76PFHuJtsQ4zgj4y4j1O03jA3tWuzVmIM67kIydr1VYERe2AfLRMPbtU86TKekJYcbwepz6ZNUglsU4LaoRNdZZ5w@BqunNIQ9sQEm0E4ENgd192Iy2xZVkaXmdINOYQHyLmgAYM9nGOo90wuc@6HzI/ZioQ2FIYLrbrf/@dBawsYtxlmx1mraPBl8ncBxoEbhY36n8psO8OHVGGYhox/BD@6TI/Gh@CoRocsl8/DQy24pfwe2wzGrjsuORo0IgdijRlqywGw0KrIW6F6rI66KXvcvmyGVoK0Qre@qmR2GZ@jDTkWnQavdtWVDtQdiRXYU7sRX358XMbskRxGZOkoM/ahQqMrOIeohUOK22Ml5zscbH0ujo066gnfhILSWxyDW5WaeGo1iKCHyFdwpQbJZOCEm9nxfztm3oH7f@GYy4PDA6j7Nks@MRLXrQW07CEh73Sj6LtEu0X88nrxiflnt3jfmAKtJgBWMnoc3zWNIigKqvsOqS84ZGwE4PohjTih9WwVPuWmpAMHxJ/Rw@FksJwLuJjDUfDhZG7oCXsumn2K1p5ZkjBfet5MgcASwaVSV3Hdju9UTzcRqLQihWCbn4RpD1tSSJAqEECt2PC9Orl2MGqXAKmH6JiD0RqToJ8PPSMViz7STizmsO7h10ZD5XdUuYuXCYT3aa9wXcO9zNrvk9peY7aozBHbMANLulqRQW21iKAnBpRjqXJOXWqGucgM7WdNq9VjYV1Z@ALtiwFt@2VVs8FOV7920aF2xr25sMGs500U055hflKrDoyP43z0l@8xxhQbuOSosbfWuBWp6u3DqKpZDBOFCUi6@ejxlhvfVfCUKoCwDQTCbyBsrDmoLy39TE4GcxJxplpWM90k82NEFk00JdVHgCa6nD2gV0cMbR42dCuYQWiUaa1stY9BHPC@O6j/JRhURlhOuurTD7@Isp3Jr1CkAm48b2ow1VejDh5tuCyhG4HVXPE3W0xzws@aVn2lbHmwL37n@nMTn9y9N/6uAMH8V04LuJo3JepSsUQZYV4INV3kH5G@5JRnoko2bl88PU2ssXVlvbbeWN/@4QcJvRdPlx/@BA "Rust – Try It Online")
[Answer]
# C, score = 56
content of `a.c`:
```
typedef void V;typedef char C;typedef long L;typedef unsigned long U;
#define R return
#define W while
#define S static
#include<sys/syscall.h>
#define h1(f,x    )({L r;asm volatile("syscall":"=a"(r):"0"(SYS_##f),"D"(x)              :"cc","rcx","r11","memory");r;})
#define h3(f,x,y,z)({L r;asm volatile("syscall":"=a"(r):"0"(SYS_##f),"D"(x),"S"(y),"d"(z):"cc","rcx","r11","memory");r;})
#define read(a...) h3(read ,a)
#define write(a...)h3(write,a)
#define exit(a...) h1(exit ,a)
S V P(U x){C s[32],*p=s+32;*--p='\n';do{*--p='0'+x%10;x/=10;}W(x);write(1,p,s+32-p);}
S V mc(V*x,V*y,L n){C*p=x,*q=y;for(L i=0;i<n;i++)p[i]=q[i];}
#define min(x,y)({typeof(x)_x=(x),_y=(y);_x+(_y-_x)*(_y<_x);})
#define t(x,i,j)x[(i)*(n+n-(i)+1)/2+(j)] //triangle indexing
#define x(i,j)t(x,i,j)
#define y(i,j)t(y,i,j)
#define z(i,j)t(z,i,j)
#define N 4096 //max
L n;U ka[N+1],c[N],x[N*(N+1)/2],y[N*(N+1)/2],z[N*(N+1)/2];
V _start(){
 C s[1<<20];L r=0;U v=0;
 W(0<(r=read(0,s,sizeof(s))))for(L i=0;i<r;i++)if('0'<=s[i]&&s[i]<='9'){v=s[i]-'0'+10*v;}else{ka[n++]=v;v=0;}
 n--;U k=*ka,*a=ka+1;
 for(L i=n-1;i>=0;i--)for(L j=i-1;j>=0;j--)x(j,i)=x(j+1,i)-a[j]+a[i];
 for(L i=0;i<n;i++)for(L j=i+1;j<n;j++)y(i,j)=y(i,j-1)+a[j]-a[i];
 for(L i=n-1;i>=0;i--)for(L j=i+1;j<n;j++){
  U v=~0ul,*p=&x(i,i),*q=&y(i,j);for(L l=i;l<j;l++){v=min(v,*p+++*q);q+=n-l;} //min(v,x(i,l)+y(l,j));
  z(i,j)=v;}
 mc(c,z,8*n);
 for(L m=1;m<k;m++)for(L j=n-1;j>=m;j--){
  U v=~0ul,*p=&z(j,j);for(L i=j-1;i>=m-1;i--){v=min(v,c[i]+*p);p-=n-i;} //min(v,c[i]+z(i+1,j))
  c[j]=v;}
 P(c[n-1]);exit(0);}
```
shell script to compile and test the above:
```
#!/bin/bash -e
clang -O3 -nostdlib -ffreestanding -fno-unwind-tables -fno-unroll-loops -fomit-frame-pointer -oa a.c
strip -R.comment -R'.note*' a;stat -c'size:%s' a
t(){ r="$(echo "$1"|./a)";if [ "$r" != "$2" ];then echo "in:$1, expected:$2, actual:$r";fi;} #func tests
t '1 0 2 4 6 8' 12
t '3 0 1 10 11 20 21 22 30 32' 23
t '5 0 1 3 6 8 11 14' 3
t '6 0 1 3 6 8 14 15 18 29 30 38 41 45 46 49 58 66 72 83 84' 49
t '2 0 7 9' 2
for n in 1176 1351 1552 1782 2048;do #perf test
 echo "n:$n";a=0 inp="$((2*n/3))" RANDOM=1;for i in `seq $n`;do inp="$inp $a";a=$((a+=RANDOM%1000));done
 ulimit -t10 -v1048576;time ./a<<<"$inp"
done
```
~~n=776 takes 6.2s, n=891 takes 12s~~
~~n=1176 takes 5.9s, n=1351 takes a little over 10s~~
n=1351 takes 8.7s, n=1552 takes more than 10s
(with k=2\*n/3) on my `Intel(R) Core(TM) i3-2375M CPU @ 1.50GHz`
[Answer]
# C++, score = 53
The solution I had said in the comment. `O(n²×k)`. (now I deleted it because it is no longer necessary) Probably can be reduced to `O(n×k)`.
The input is pretty flexible, on the first line, the first number is `k`, the other numbers are items of array `a`, but if it encounters any close-parentheses it stops reading input. So input like `K = 1, A = [0, 2, 4, 6, 8] : 12` is accepted.
```
// https://codegolf.stackexchange.com/questions/149029/build-an-electrical-grid
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <climits>
bool read(std::istream& str, int& x) {
    char ch;
    do {
        if (str >> x) return true;
        if (str.eof()) return false;
        str.clear(); // otherwise it's probably int parse error
    } while (str >> ch && ch != ']' && ch != ')' && ch != '}');
    // ignore 1 character, but treat any close parentheses as end of input
    // cannot read anything now
    return false;
}
int main() {
    int k; std::vector<int> a;
    //{ Read input
    std::string st; std::getline(std::cin, st);
    std::stringstream sst (st);
    read(sst, k);
    int x;
    while (read(sst, x)) a.push_back(x);
    //}
    std::vector<std::vector<int>> dp (a.size(), std::vector<int>(k));
    // dp[n][k] = min distance you can get for cities [n..a.size()-1]
    // and [k+1] power plants, and city [n] has a power plant.
    // sum_array[x] = sum of coordinates of cities [x..a.size()-1]
    std::vector<int> sum_array (a.size()+1);
    sum_array.back() = 0;
    for (int n = a.size(); n --> 0;)
        sum_array[n] = sum_array[n+1] + a[n];
    for (int n = a.size(); n --> 0;) {
        for (int k1 = k; k1 --> 0;) {
            if (k1 == 0) {
                int nWire = a.size() - 1 - n;
                dp[n][k1] = sum_array[n+1] - nWire * a[n];
            } else {
            // unindent because my screen width is limited
dp[n][k1] = INT_MAX / 2; // avoid stupid overflow error (in case of -ftrapv)
// let [n1] be the next position for a power plant
int first_connect_right = n; // < lengthy variable name kills screen width
// ^ lengthy comment kills screen width
for (int n1 = n + 1; n1 < (int)a.size(); ++n1) {
    while (a[first_connect_right]-a[n] < a[n1]-a[first_connect_right]) ++first_connect_right;
    int nRightWire = n1 - first_connect_right, nLeftWire = first_connect_right - 1 - n;
    dp[n][k1] = std::min(dp[n][k1],
        a[n1]*nRightWire-(sum_array[first_connect_right]-sum_array[n1]) +
        (sum_array[n+1]-sum_array[first_connect_right])-a[n]*nLeftWire +
        dp[n1][k1-1]
    );
}
            }
        }
    }
    int ans = INT_MAX;
    for (int n = a.size()+1-k; n --> 0;) {
        ans = std::min(ans, dp[n].back() + a[n]*n-sum_array[0]+sum_array[n]);
    }
    std::cout << ans << '\n';
    return 0;
}
```
[Try it online!](https://tio.run/##hVnZbhzJEXznV7RhYEWuSKruYyUL8KPh48EwYAMyLYyGTXLAYQ89M9Thhb59HRHZPLQi7F1AwaquIysrMzKzZnl7e3K5XP7yy6tXw9V@f7v76dWr5eZ8vNysL053@8Xyevy8vFpMl@PpcnPz6t93426/2ky7Vz51F/qrD3er9fnJYjoZ1@Nyv10tF@uTy@3q/ODgt6tpub47H4c3q81uvx0XN2@f9H3E6M32aQ/GrKbLb3q@n7Zcr25W@93bg4MPm816wOfzw93@/KefVjb2hwF4PKym/Q/D56Ph54ODAf/hAFv889pa5xv0D/N/q4sBC2y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do2sS3Vk54N@ExbmQZ0P9YbiM2LSvKz3AqDe8XEc2YmeJzSu6T0MaaXiJbMk1vfAQv2BHvR7hn7vEQbxTuf7l8Yjkef6oeodvPMdV/N6Zr2KwyfJGen5Qr27AmNWG/ltEGbGd6hZ76RdDwTEWCQPCvaqdjE9JP6cReyq7zvL306EQNwX6QXzlY5CZ0bxD9LlQj/CNeqdiOE9a37X70YoluXnQP0CC8y0787ErQkL7azzR1a1s@y981lB46vJzR/ruB@05DS@289g6LUfxyyfRUt1G1D1L8wpZP1qVpK1cT08D8MAEUQq/YJeyA@gX/Eof06gXwMj@aG3@b7heJIP7KP9@S6r703@20kvXii@AFbmOx3lN/MwRE3VhfyZQvfDi1M7q/4gNq2DcK75EIf7UiB/9l8 "C++ (gcc) – Try It Online")
[Generate random test cases.](https://codegolf.stackexchange.com/questions/149029/build-an-electrical-grid?noredirect=1#comment365807_149029) (input `N` and optionally city range, `1000×N` by default)
[Answer]
# C#, score = 23
I am sure this is not going to win this challenge, I just wanted to post a first (and very basic) answer to encourage other people to post their algorithms and improve mine. This code must be compiled as a console project that uses the [Combinatorics package](https://github.com/eoincampbell/combinatorics) from NuGet. The main method contains some calls to the `Build` method to test the proposed cases.
```
using Combinatorics.Collections;
using System;
namespace ElectricalGrid
{
    class Program
    {
        static void Main(string[] args)
        {
            if (Build(1, new long[] { 0, 2, 4, 6, 8 }) == 12)
                Console.WriteLine("OK");
            else
                Console.WriteLine("ERROR");
            if (Build(3, new long[] { 0, 1, 10, 11, 20, 21, 22, 30, 32 }) == 23)
                Console.WriteLine("OK");
            else
                Console.WriteLine("ERROR");
            if (Build(5, new long[] { 0, 1, 3, 6, 8, 11, 14 }) == 3)
                Console.WriteLine("OK");
            else
                Console.WriteLine("ERROR");
            if (Build(6, new long[] { 0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84 }) == 49)
                Console.WriteLine("OK");
            else
                Console.WriteLine("ERROR");
            Console.ReadKey();
        }
        static long Build(int k, long[] a)
        {
            var combs = new Combinations<long>(a, k);
            var totalDist = long.MaxValue;
            foreach (var c in combs)
            {
                long tempDist = 0;
                foreach (var i in a)
                {
                    var dist = long.MaxValue;
                    foreach (var e in c)
                    {
                        var t = Math.Abs(i - e);
                        if (t < dist) dist = t;
                    }
                    tempDist += dist;
                }
                if (tempDist < totalDist) totalDist = tempDist;
            }
            return totalDist;
        }
    }
}
```
Really simple explanation: for each combination `c` of `k` elements from `a`, calculate the sum of the distances from each element of `a` to the nearest element in `c`, and return the combination with the least total distance.
One-liner version of the `Build` method (probably slower than the original, expanded version; this needs to add a reference to `System.Linq`):
```
static long Build(int k, long[] a)
{
    return new Combinations<long>(a, k).Min(c => a.Sum(i => c.Min(e => Math.Abs(i - e))));
}
```
[Answer]
# C++, score = 48
```
#include <stdio.h>
#include <queue>
#include <algorithm>
typedef long long ull;
typedef unsigned int uint;
uint A[1<<20];
ull S[1<<20];
double ky = 1;
struct point {
    ull dist;
    int n;
    inline point() {}
    inline point(ull dist, int n): dist(dist), n(n) {}
    inline double res() const{
        return dist + n * ky;
    }
    inline int operator<(const point& other) const {
        return res() < other.res();
    }
} V[1<<20];
inline ull f(int L, int R) {
    int m = L+R+1 >> 1;
    return (S[R]-S[m]) - A[m]*(R-m) +
           A[m]*(m-L) - (S[m]-S[L]);
}
int main() {
    int N, K, i, j, p;
    scanf ("%d%d", &N, &K);
    ull s = 0;
    for (i=1; i<=N; i++) {
        scanf ("%u", A+i);
        S[i] = s += A[i];
    }
    double kyL = 0, kyH = 1e99;
    point cL, cR;
    for (int step=0; step++<50; ky = std::min(ky*2, (kyL+kyH)*.5)) {
        for (i=1; i<=N; i++) {
            point tmp(f(0,i), 1);
            for (j=1; j<i; j++) {
            //printf("ky=%f [%d]=%d %I64d %f\n", ky, i, tmp.n, tmp.dist, tmp.res());
                point cmp = V[j];
                cmp.dist += f(j, i);
                cmp.n ++;
                if (cmp<tmp) tmp=cmp;
            }
            //printf("ky=%f [%d]=%d %I64d %f\n", ky, i, tmp.n, tmp.dist, tmp.res());
            V[i] = tmp;
        }
        if (V[N].n == K) {
_:          return! printf("%I64d", V[N].dist);
        }
        if (V[N].n > K) {
            kyL = ky;
            cL = V[N];
        } else {
            kyH = ky;
            cR = V[N];
        }
        //printf("ky=%f %d %I64d %f\n", ky, V[N].n, V[N].dist, V[N].res());
        //getch();
    }
    V[N].dist = (double)cL.dist / (cR.n-cL.n) * (K-cL.n) +
                (double)cR.dist / (cL.n-cR.n) * (K-cR.n) + .5;
    printf("%I64d", V[N].dist);
}
```
Usage input:
N K A[1] A[2] ... A[N]
[Answer]
# [Ruby](https://www.ruby-lang.org/), score = 23
```
->a,l{d=l.map{|x|l.map{|y|(x-y).abs}};[*0...l.size].combination(a).map{|r|r.map{|w|d[w]}.transpose.sum{|r|r.min}}.min}
```
[Try it online!](https://tio.run/##LYtNCoMwFISvkqWW@LAaraXYi4QsYlUQNEqiqDU5e/qoLmb4mB@9VLtvSx@9Je2PuuxhkNNhN3vBboMt2kOQlXHuxW8xAPRgum8j4DMOVafk3I0qkOG511afsNqar8LBrKUy02gaMMtw9Z1y7u9@Ii3PKY8puVOSUpJTUiAzVIZCTp5YYJ8iMxwxzBnOGOYZZjnyI8EbvgsmhP8B "Ruby – Try It Online")
I don't think it's going to win, but I wanted to give it a try.
[Answer]
# [JavaScript (ES6) (Node.js)](https://nodejs.org), score = 10
New Algorithm, will explain if it actually works this time.
```
const {performance} = require('perf_hooks');
class Connection{
    constructor(left,index,length,right){
        if(typeof right === 'undefined'){
            this._distance = 0;
        } else {
            this._distance = typeof left === 'undefined' ? 0 :
                    Math.abs(right - left);
        }
        var half = Math.floor(length/2);
        if(length % 2 < 1){
            this._magnitude = half - Math.abs(index - half + 1);
        } else {
            var temp = index - half;
            this._magnitude = half - Math.abs(temp >= 0 ?temp:temp + 1);
        }
        this._value = this.distance * this.magnitude;
    }
    get distance(){return this._distance;};
    get magnitude(){return this._magnitude;};
    set magnitude(value){
        this._magnitude = value;
        this._value = this.distance * this.magnitude;
    };
    valueOf(){return this._value};
}
class Group{
	constructor(...connections){
        this._connections = connections;
		
		this._max = Math.max(...connections); //uses the ValueOf to get the highest Distance to the Left
	}
	get connections(){return this._connections;};
	get max(){return this._max;};
    cutLeft(index){
            for(let i=1,j=index-1;;i++){
                
                if(typeof this.connections[j] === 'undefined' || this.connections[j].magnitude <= i){
                    break;
                }
                this.connections[j].magnitude = i;
                j--;
            }
    }
    cutRight(index){
            for(let i=0,j=index;;i++){
                
                if(typeof this.connections[j] === 'undefined' || this.connections[j].magnitude <= i){
                    break;
                }
                this.connections[j].magnitude = i;
                j++;
            }
    }
    static of(...connections){
        return new Group(...connections.map((c,i)=>new Connection(c.distance,i,connections.length)));
    }
	split(){
        var index = this.connections.findIndex(c=>c.valueOf() == this.max);
        if(index < 0){
            return;
        }
        var length = this.connections.length;
        var magnitude = this.connections[index].magnitude;
        this.cutLeft(index);
        this.cutRight(index);
        this._max = Math.max(...this.connections);
	}
    center(){
        if(typeof this._center === 'undefined'){
            this._center = this.connections.reduce((a,b)=>a==0?b.valueOf():a.valueOf()+b.valueOf(),0);
        }
        return this._center;
    }
    valueOf(){return this._max;};
    toString(){
        var index = this.connections.findIndex(c=>c.valueOf() == this.max);
        var value = this.connections[index].magnitude;
        var ret = '';
        for(let i = 0;i<value;i++){
            ret += this.connections.map(c=>{return (i<c.magnitude)?c.distance:' ';}).reduce((a,b)=>a==''?b:a+'-'+b,'') + '\n';
        }
        return ret;
    };
}
function crunch(plants, cities){
	var found = [];
    var size = cities.length;
    cities = cities.map((city,i,arr)=> new Connection(city,i,size,arr[i+1])).slice(0,cities.length-1);
    var group = new Group(...cities);
    for(;plants>1;plants--){
    group.split();
    }
    console.log(`Wire Length Needed: ${group.center()}`);
}
function biggestGroup(groups){
	return groups.find(g => g[g.length-1].orig - g[0].orig);
}
function* range (start, end, limit) {
    while (start < end || typeof limit !== 'undefined' && limit-- > 0) {
        yield start
        start += 1 + Math.floor(Math.random()*100);
    }
}
function* cities (score){
	let n = Math.floor(Math.pow(2,score/5));
	var start = 0;
	while (n-- > 0 && start <= (1000 * n)) {
		yield start;
        start += 1 + Math.floor(Math.random()*100);
    }
}
if(typeof process.argv[3] === 'undefined'){
    crunch(1,[0, 2, 4, 6, 8]);
    console.log("Correct Answer: 12");
    crunch(3,[0, 1, 10, 11, 20, 21, 22, 30, 32]);
    console.log("Correct Answer: 23");
    crunch(5,[0, 1, 3, 6, 8, 11, 14]);
    console.log("Correct Answer: 3");
    crunch(6,[0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84]);
    console.log("Correct Answer: 49");
    crunch(2, [0, 21, 31, 45, 49, 54]);
    console.log("Correct Answer: 40");
    crunch(2, [0, 4, 7, 9, 10]);
    console.log("Correct Answer: 7");
    crunch(2, [0, 1, 3, 4, 9]);
    console.log("Correct Answer: 6");
    
    var max = 0;
    var min = Number.POSITIVE_INFINITY;
    var avg = [];
    
    var score = typeof process.argv[2] === 'undefined' ? 60 : process.argv[2];
    for(j = 0; j<10; j++){
        var arr = []; for(let i of cities(score)) arr.push(i);
        var plants = Math.floor(1 + Math.random() * arr.length);
        console.log(`Running: Test:${j} Plants: ${plants}, Cities ${arr.length}, Score: ${score}`);
        // console.log(`City Array: [${arr}]`);
        var t0 = performance.now();
        crunch(plants,arr);
        var t1 = performance.now();
        time = (t1-t0)/1000;
        console.log(`Time Taken = ${time} seconds`);
        avg.push(time);
        max = Math.max(time,max);
        min = Math.min(time,min);
    }
    console.log(`Bench: ${avg.reduce((a,b)=>a+b,0)/avg.length} Max: ${max} Min: ${min} Total: ${avg.reduce((a,b)=>a+b,0)}`);
} else {
    var plants = process.argv[2];
    var arr = process.argv.slice(3);
    console.log(`Running: Plants: ${plants}, Cities ${arr.length}`);
    var t0 = performance.now();
    crunch(plants,arr);
    var t1 = performance.now();
    time = (t1-t0)/1000;
    console.log(`Time Taken = ${time} seconds`);
}
```
[Try it online!](https://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jycpu1jR8NEbEOVrlAoH5ANZFP6CtqgNrj8LC4DX51JK859x56ZCDErIefS0YlbTBI@5bZCgH@dL0LNRpLaWm9s3t9wuZ4wmbiNJO2dYjwuMUp18h57X2hGFIHK1y4JjEFnnGsaw2xJM8HOTR6qdPFWbvYiMlolRwsTDlYuL0K/0DBdvQ17llqhKD5AXtwIj0aEHyPvLAnjFkoxixck@so8Wa7pMhCrn@yKoRbJd6L8axPp@1Ld0N650G3Z6h91nqeXVGyLUKeio6tkfFNUbF@fHx0/gE "JavaScript (Node.js) – Try It Online")
Run the same way as the other one.
# [JavaScript (ES6) (Node.js)](https://nodejs.org), pretest score = 12
Outline of the algorithm:
The program first maps the Data into the City Class, which maps a few data points:
* city - the absolute distance of the city
* left - the distance of the closest city to the left
* right - distance of the closest city to the right
* index - (deprecated) index in original city array
the array is then thrown into the Group class, which has the following:
* cities - the city array
* dist - the distance spanning the group
* max - the largest left connection in the group
* split()
	+ returns an array containing sub groups split along the largest connection connected to the center city in the group
	+ if there are 2 center nodes (an even length group) it chooses from those 3 connections
	+ (\*note\*: this will drop any groups with less than two cities)
* center()
	+ returns the best wire value for the group
	+ working on a solution to skip iterating over each city left for this step
	+ now with 50% less mapping
Now the algorithm proceeds to split the groups as long as it has 2 or more 
power plants to place.
Finally it maps the groups to the it's centers, and sums them all up.
## How to run:
### Run using Node.js (v9.2.0 is what was used for creation)
running the program using generated test cases for score 70:
```
node program.js 70
```
running the program using 1 power plant and cities [0,3,5]:
```
node program.js 1 0 3 5
```
## Code:
```
const {performance} = require('perf_hooks');
class City{
	constructor(city, left, right, i){
		this._city = city;
		this._index = i;
		this._left = typeof left === 'undefined' ? 0 : city - left;
		this._right = typeof right === 'undefined' ? 0 : right - city;
	}
	get city(){return this._city;};
	get index(){return this._index;};
	get left(){return this._left;};
    get right(){return this._right;};
    set left(left){this._left = left};
    set right(right){this._right = right};
	valueOf(){return this._left;};
}
class Group{
	constructor(...cities){
        this._cities = cities;
        // console.log(cities.map(a=>a.city).reduce((a,b)=>a===''?a+(b<10?' '+b:b):a+'-'+(b<10?' '+b:b),""));
        // console.log(cities.map(a=>a.left).reduce((a,b)=>a===''?a+(b<10?' '+b:b):a+'-'+(b<10?' '+b:b),""));
        // console.log(cities.map(a=>a.right).reduce((a,b)=>a===''?a+(b<10?' '+b:b):a+'-'+(b<10?' '+b:b),""));
        // console.log("+==+==+==+==+==+==+==+==+==+==+==+==")
		this._dist = cities[cities.length-1].city - cities[0].city;
		this._max = Math.max(...cities); //uses the ValueOf to get the highest Distance to the Left
	}
	get dist(){return this._dist;};
	get cities(){return this._cities;};
	get max(){return this._max;};
	split(){
        //var index = this.cities.findIndex(city=>city.left == this.max);
        //this.cities[index].left = 0;
        // console.log(`Slicing-${this.max}-${index}------`)
        var centerIndex = this.cities.length / 2;
        var splitIndex = Math.floor(centerIndex);
        if(centerIndex%1 > 0){
            var center = this.cities[splitIndex];
            if(center.right > center.left){
                splitIndex++;
            }
        } else {
            var right = this.cities[splitIndex];
            var left = this.cities[splitIndex-1];
            if(left.left > Math.max(right.right,right.left)){
               
                splitIndex--;
            } else if(right.right > Math.max(left.left,left.right)){
                
                splitIndex++;
            }
        }
        // console.log(splitIndex);
        this.cities[splitIndex].left = 0;
        this.cities[splitIndex-1].right = 0;
        var leftCities = [...this.cities.slice(0,splitIndex)];
        var rightCities = [...this.cities.slice(splitIndex)];
        // var center = this.cities[]
        if(leftCities.length <= 1){
            if(rightCities.length <= 1){
                return [];
            }
            return [new Group(...rightCities)]
        }
        if(rightCities.length <= 1){
            return [new Group(...leftCities)];
        }
        return [new Group(...leftCities), new Group(...rightCities)];
	}
    center(){
        if(typeof this._center === 'undefined'){
            if(this.cities.length == 1){
                return [0];
            }
            if(this.cities.length == 2){
                return this.cities[1].left;
            }
            var index = Math.floor(this.cities.length/2);
            this._center = this.cities.reduce((a,b)=> {
                // console.log(`${a} + (${b.city} - ${city.city})`);
                return a + Math.abs(b.city - this.cities[index].city);
            },0);
            // console.log(this._center);
        }
        
        return this._center;
    }
	valueOf(){return this._max;};
}
function crunch(plants, cities){
	var found = [];
    var size = cities.length;
    cities = cities.map((city,i,arr)=> new City(city,arr[i-1],arr[i+1],i));
	var groups = [new Group(...cities)];
	// console.log(groups);
    for(;plants>1;plants--){
        var mapped = groups.map(g=>g.center()-g.max);
        var largest = Math.max(...groups);
        // console.log('Largest:',largest)
        // console.log(...mapped);
		var index = groups.findIndex((g,i)=> mapped[i] == g.center() - g.max && g.max == largest);
		// console.log(index);
        groups = index == 0 ? 
            [...groups[index].split(),...groups.slice(index+1)]:
            [...groups.slice(0,index),...groups[index].split(),...groups.slice(index+1)];
    }
    // console.log(`=Cities=${size}================`);
    // console.log(groups);
    size = groups.map(g=>g.cities.length).reduce((a,b)=>a+b,0);
    
    // console.log(`=Cities=${size}================`);
    var wires = groups.map(g=>g.center());
    
    // console.log(...wires);
    // console.log(`=Cities=${size}================`);
    console.log(`Wire Length Needed: ${wires.reduce((a,b)=>a + b,0)}`);
}
function biggestGroup(groups){
	return groups.find(g => g[g.length-1].orig - g[0].orig);
}
function* range (start, end, limit) {
    while (start < end || typeof limit !== 'undefined' && limit-- > 0) {
        yield start
        start += 1 + Math.floor(Math.random()*100);
    }
}
function* cities (score){
	let n = Math.floor(Math.pow(2,score/5));
	var start = 0;
	while (n-- > 0 && start <= (1000 * n)) {
		yield start;
        start += 1 + Math.floor(Math.random()*100);
    }
}
if(typeof process.argv[3] === 'undefined'){
    crunch(1,[0, 2, 4, 6, 8]);
    console.log("Correct Answer: 12");
    crunch(3,[0, 1, 10, 11, 20, 21, 22, 30, 32]);
    console.log("Correct Answer: 23");
    crunch(5,[0, 1, 3, 6, 8, 11, 14]);
    console.log("Correct Answer: 3");
    crunch(6,[0, 1, 3, 6, 8, 14, 15, 18, 29, 30, 38, 41, 45, 46, 49, 58, 66, 72, 83, 84]);
    console.log("Correct Answer: 49");
    crunch(2, [0, 21, 31, 45, 49, 54]);
    console.log("Correct Answer: 40");
    crunch(2, [0, 4, 7, 9, 10]);
    console.log("Correct Answer: 7");
    
    var max = 0;
    var min = Number.POSITIVE_INFINITY;
    var avg = [];
    
    var score = typeof process.argv[2] === 'undefined' ? 60 : process.argv[2];
    for(j = 0; j<10; j++){
        var arr = []; for(let i of cities(score)) arr.push(i);
        var plants = Math.floor(1 + Math.random() * arr.length);
        console.log(`Running: Test:${j} Plants: ${plants}, Cities ${arr.length}, Score: ${score}`);
        var t0 = performance.now();
        crunch(plants,arr);
        var t1 = performance.now();
        time = (t1-t0)/1000;
        console.log(`Time Taken = ${time} seconds`);
        avg.push(time);
        max = Math.max(time,max);
        min = Math.min(time,min);
    }
    console.log(`Bench: ${avg.reduce((a,b)=>a+b,0)/avg.length} Max: ${max} Min: ${min} Total: ${avg.reduce((a,b)=>a+b,0)}`);
} else {
    var plants = process.argv[2];
    var arr = process.argv.slice(3);
    console.log(`Running: Plants: ${plants}, Cities ${arr.length}`);
    var t0 = performance.now();
    crunch(plants,arr);
    var t1 = performance.now();
    time = (t1-t0)/1000;
    console.log(`Time Taken = ${time} seconds`);
}
```
[Try it online!](https://tio.run/##vVh7b9s2EP/b/hRckNVSLTuWnaRtXKfYsgcCtGmxBh0Gw2hkm5aZOpInyXnM1WfP7khKImnJcTdsRmLR5N3vHrw7HnXt3XrxJGLLpBWEU/r4OAmDOCHrJY1mYXTjBROakgGJ6J8rFlGrgfOf52H4JW7Y/Xp9svDimJyx5GFdr3HWaDVJwsiawJRDFnSWOCRi/hwezAaaWjJncfszLgMsPvr5JAum9B5mWTGFADCTPCxpOCPi12BAGisgnbGAThvkDemQE45EWpyi4OaCC3b5s5RfrLUyjdJ6vebThP@07HVEk1UUkEL3ftoXBFxnk4JP5iSok0nB9QQCAh@k4eJNIj6ZUcUZEn7Za809@FDIBBj/zggzT/AnkNZrt95iRd/PqhRLs739NQpXS2Nz2@02OIHRGHaUyE/uG5gWOwuDfr58cEAQIVzQ9iL0LbHcvvGWljc49RDuwW5HdLqaUMvynLENs7BTjcYbr2mNX7udNw3Sa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P5duQsAcpSfiAK8WB/jRGcDoxPlvDbgkqG/ka0qKmwcSNqjvOc/zd6YRjcsYjnV1W4bhEDLuPc5VbuqoTG8zvgwT2HHxEXlE7p9ARqKJdi@gAqJnohRRy1@IyZj6Eoslu6GkqPrFlKtFs@gSj3h75ypQvheMUAx9scjnXs5yTyAp8SC@5lUeIQGkwdsmA3LLHl@XA3Z4tsnbxGAvL1a/5OBinJd8ZLFUgjvtBq8cuDctA8MLqYEo6VzwnkJhzI2Ykhzjo@BO2m4Y1lP3c7WXikuv6ynFrxJIwoumUBd8BAPzb5cBneWV2Hkx0c5QVUSOcNZ02aGgi90Qxp9YBYIL9DnpPARnNqNcWQ/r@zpGhqllE4oXHchsJzO@yNKvoaeRK5zrDjkK5DDh1y7JCXo5LY2zsLo4hOEvJDEN/R6IS43b2MTKD0OIoLf/iAZxdB8QnIPRj3ujsBd3sG8FEG3BPqCXT3cCc0E@x4Ewysdo/gH8bdV1JVGB8C0SHMHwLZIcwfwdwxjF@AOS@B@@VuChy@MjQA9qH0TC8TgfA7wnXK4cCIFw55hd7fCefFnlq6xNF8X1yW@ATD0L9Y3Yzhcv3h/cfzy/NPP38@v/jl/OL88o@Czrv1lYal6FowO4p3plpEdkclb0@P8fWpQSZvT9hbXHPtyPVrF7@bTaOzgIZGaMGJMXEZAbHyNY/IaBup2stVPLeY0WKIfkVP9Tz1snyDpEUAeewUAFqR/m0VBCzwT8gl9h776@uUfODgWKuFmNQh8gYJXXEOCLMfUU2k4/qmV4aSSQcUVF6otwOoQ6oeWmeJDaDB727nT9gN7piVuK2kYx9gnaow8hIpL70vFENkf42MKYkp0ExjVWuIDeFvpFDmjbd/uOrofZ@IPkHBAknBAlttODSVfqRgO/oOZZZ1BAe4IF0NwPdIi@/IyDsW8DELUnIZJt5iG4o4UdXXRVr4bMSvHp/qsmylemUnfR5EO4aO2rNsi5KqCHkqOioj45uiIn18fHT/Bg "JavaScript (Node.js) – Try It Online")
I will clean up the commented out code over the next couple of days as I am still working on this, just wanted to see if this was passing more than just the small cases.
[Answer]
# C (non-competing, pretest score = 76)
This is an attempt to translate @AndersKaseorg's second Rust solution to C.
```
typedef void V;typedef char C;typedef long L;
#define R return
#define W while
#define S static
#include<sys/syscall.h>
#define exit(x)     ({L r;asm volatile("syscall":"=a"(r):"0"(SYS_exit ),"D"(x)              :"cc","rcx","r11","memory");r;})
#define read(x,y,z) ({L r;asm volatile("syscall":"=a"(r):"0"(SYS_read ),"D"(x),"S"(y),"d"(z):"cc","rcx","r11","memory");r;})
#define write(x,y,z)({L r;asm volatile("syscall":"=a"(r):"0"(SYS_write),"D"(x),"S"(y),"d"(z):"cc","rcx","r11","memory");r;})
S V P(L x){C s[32],*p=s+32;*--p='\n';do{*--p='0'+x%10;x/=10;}W(x);write(1,p,s+32-p);}
#define N 0x100000 //max
#define INF (-1ul>>1)
S L cost[N],nk1,*am; //nk1:n-k+1, am:input's partial sums offset with the current "m" in _start()
S L f(L i,L j){if(i+1>=j&&cost[j]!=INF){L h=(i-j+1)>>1;R cost[j]+am[i+1]-am[j+h]-am[i-h+1]+am[j];}else{R INF;}}
S V smawk(L sh,L*c,L nc,L*r){ //sh:shift,c:cols,r:result
 L n=nk1>>sh;if(!n)R;
 L m=n>>1,u[m];
 if(n<nc){
  L ns=0,s[nc],sk[nc],*skp=sk;
  for(L jk=0;jk<nc;jk++){
   L j=c[jk];W(ns>0&&f(~(~(ns-1)<<sh),j)<=f(~(~(ns-1)<<sh),s[ns-1])){--ns;--skp;}
   if(ns<n){s[ns++]=j;*skp++=jk;}
  }
  smawk(sh+1,s,ns,u);for(L i=0;i<m;i++)u[i]=sk[u[i]];
 }else{
  smawk(sh+1,c,nc,u);
 }
 L l=0,ish=(1<<sh)-1,dsh=1<<(sh+1);
 for(L i=0;i<m;i++){
  L k=u[i],bj=l,bc=f(ish,c[l]);
  for(L j=l+1;j<=k;j++){L h=f(ish,c[j]);if(h<bc){bc=h;bj=j;}}
  *r++=bj;*r++=k;l=k;ish+=dsh;
 }
 if(n&1){
  L nsh=~(~(n-1)<<sh),bj=l,bc=f(nsh,c[l]);
  for(L j=l+1;j<nc;j++){L h=f(nsh,c[j]);if(h<bc){bc=h;bj=j;}}
  *r=bj;
 }
}
S L inp(L*a){
 L n=-1,l,v=0;C b[1<<20];
 W(0<(l=read(0,b,sizeof(b))))for(L i=0;i<l;i++)if('0'<=b[i]&&b[i]<='9'){v=b[i]-'0'+10*v;}else{a[++n]=v;v=0;}
 R n;
}
V _start(){
 S L a[N];L n=inp(a),k=*a,s=0;for(L i=0;i<n;i++){a[i]=s;s+=a[i+1];}a[n]=s;
 *cost=0;for(L i=1,l=n+1-k;i<l;i++)cost[i]=INF;
 S L c[N];L nc=n+1-k;for(L i=0;i<nc;i++)c[i]=i;
 S L r[N];nk1=n-k+1;for(L m=0;m<k;m++){am=a+m;smawk(0,c,nc,r);for(L i=n-k;i>=0;i--)cost[i]=f(i,r[i]);}
 P(cost[n-k]);exit(0);
}
```
Compile with:
```
#!/bin/bash -e
clang -O3 -nostdlib -ffreestanding -fno-unwind-tables -fno-unroll-loops -fomit-frame-pointer -oa a.c
strip -R.comment -R'.note*' a
```
[Answer]
# [Clean](http://clean.cs.ru.nl/Clean), score = 65
```
module main
import StdEnv, System.IO
parseArgs :: *World -> ((Int, {#Int}), *World)
parseArgs world
    # (args, world)
        = nextArgs [] world
    # args
        = reverse args
    # (k, a)
        = (hd args, tl args)
    = ((toInt k, {toInt n \\ n <- a}), world)
where
    nextArgs :: [String] *World -> ([String], *World)
    nextArgs args world
        # (arg, world)
            = evalIO getLine world
        | arg == ""
            = (args, world)
        = nextArgs [arg:args] world
minimalWeight :: Int !{#Int} -> Int
minimalWeight k a
    # count
        = size a
    # touches
        = createArray ((count - k + 3) / 2 * k) 0
    = treeWalk k count a [(0, 0, 0, 0)] touches
where
    treeWalk :: Int !Int {#Int} ![(!Int, !Int, Int, Int)] *{Int} -> Int
    treeWalk k verticies a [(weight, vertex, degree, requires) : nodes] touches
        | vertex >= verticies
            = weight
        | requires >= k
            = treeWalk k verticies a nodes touches
        # index
            = degree * k + requires
        | (select touches index) > vertex
            = treeWalk k verticies a nodes touches
        # (next, pivot)
            = (vertex + 1 + degree, verticies + requires)
        # (nodes, touches)
            = (orderedPrepend (weight, next, 0, requires + 1) nodes, update touches index (vertex + 1))
        | pivot >= k + next
            # (weight, vertex)
                = (weight + (select a next) - (select a vertex), vertex + 1)
            # nodes
                = orderedPrepend (weight, next + 1, 0, requires + 1) nodes
            | pivot == k + next
                = treeWalk k verticies a nodes touches
            # weight
                = weight + (select a (next + 1)) - (select a vertex)
            # nodes
                = orderedPrepend (weight, vertex, degree + 1, requires) nodes
            = treeWalk k verticies a nodes touches
        = treeWalk k verticies a nodes touches
    where
        orderedPrepend :: (!Int, Int, Int, Int) ![(!Int, Int, Int, Int)] -> [(Int, Int, Int, Int)]
        orderedPrepend a []
            = [a]
        orderedPrepend a [b : b_]
            # (x, _, _, _)
                = a
            # (y, _, _, _)
                = b
            | y > x
                = [a, b : b_]
            = [b : orderedPrepend a b_]
Start world
    # ((k, a), world)
        = parseArgs world
    = minimalWeight k a
```
Compile with:  
`clm -h 1024M -gci 32M -gcf 32 -s 32M -t -nci -ou -fusion -dynamics -IL Platform main`
Takes `K`, and then each element of `A`, as command-line arguments.
]