text:
Build an Electrical Grid
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 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. 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. The original constraints are N <= 300 and K <= 30, though.

2^^(x/5) : what is the meaning ? can you just provide an upper bound for N ?

@Setop For example, if your program can deal with N=21( = floor(2^(22/5)) ) in 10 seconds, but cannot deal with N=24( = floor(2^(23/5)) ), then 23 will be the score. I didn't use an upper bound, since the differences between different algorithms are too great. For example, if I set N <= 40, there will be little difference between O(KN^2) and O(KN^3), however O(2^N) will not even finish in resonable time.

This is pretty much what I do for a living, and I can tell you this much: This is not the way we design the electrical grid!

Random test generator

Excellent challenge, excellent scoring system. Well done!

Rust, score = 104
This is an implementation of the algorithm noted by Grønlund et al. (2017) 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, 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!
Rust, 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!

You've got a pretest score 61, but that's because overflow of u32. Maybe you can change to 64-bit integer type?

@ColeraSu Does it do better if I just change type Cost = u32 to type Cost = u64?

Yes. You got 63.

Wow, I had never thought of SMAWK algorithm. Nice job, you got 73.

@AndersKaseorg Impressive! The algorithm is brilliant, the programming language - not so much.

@ngn What do you have against Rust? :-(

@AndersKaseorg My only experience with Rust is this post, a few examples and a presentation on YouTube. First impressions: too verbose, imposes unnecessary abstractions, static typing only gets in the way. To be fair, Rust binaries are surprisingly fast despite their size, and I find rustc's error messages helpful. I'm actually trying to rewrite your code in C (not my favourite language either - I'm an APL/J/k fan) to see if it's any faster and I'll post as non-competing it if I'm successful.

@ngn Wow, this was definitely not intended to be an introduction to Rust. Perhaps you don’t realize how little these abstractions actually cost (and that they are not “imposed”), but you’ll find that out soon enough. To make your comparison fair, I’ve gone and turned off bounds checking on the vector accesses. As for binary size, did you try strip?

@AndersKaseorg Strip takes it from a few MB down to hundreds of kB. For comparison, my binary is a little more than 3 kB but I did go out of my way to get rid of libc.

@AndersKaseorg The current Rust source doesn't compile (or am I doing something wrong?), so I tested against the old source. The C translation I posted is about twice as fast.

@ngn It compiles fine at the TIO link. Perhaps your rustc version is too old?

@AndersKaseorg you guessed correctly, mine: 1.14.0, tio: 1.21.0

@AndersKaseorg ok, this is better - only ~50% slower than C

@ColeraSu Here’s a third algorithm that’s even faster!

@AndersKaseorg Sorry, SMAWK (autocorrect). I'd like to use it as a base for a solution, but as you used it first, I was asking if you'd object / feel like I was encroaching on your answer. It wouldn't be a literal translation of your solution (unlike one of the C ones).

@Οurous The degree of originality in your answer depends on the degree of originality in your answer, I guess?

@AndersKaseorg I'll get started then, thanks.

Congratulations on winning the first bounty!

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

I suppose this isn't code-golf?

@user202729 It's how I normally write C code - incunabulum-style.

@ngn I assume you then also normally do not use any kind of syntax highlighting?

@JonathanFrech I do, actually. I've customised my syntax/c.vim.

It doesn't work with K = 2, A = [0, 7, 9]. It outputs 7 instead of 2.

@ColeraSu Thanks. Fixed (it was an off-by-one error) and added to tests.

I'm most impressed by the fact that you can read that. Wow. Sans comments, too.

@cole This is just regular C, only denser. If you are familiar with the language, you should be able to read it without much difficulty, albeit several times slower, as one line here contains information most C programmers would spread over 5-10 lines (what a waste!). I wrote comments only for the trickiest bits.

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!
Generate random test cases. (input N and optionally city range, 1000×N by default)

If it happens to be able to solve some larger test case, I will change the necessary ints to int64_ts.

dp[runned_n,runned_k]=min{dp[runned_n-x,runned_k]+f[x,n]}, so direct dynamic programming is O(n^2*k). Maybe need to totally change way to reduce complexity?

@l4m2 Don't spoil the algorithm! (well, the bounty has not expired)

Sorry, but I don't quite know if your "spoil" mean "throw away" or "steal" or both. Can find both meaning. I don't quite know this word. (I've also thought bounty means bound)

@l4m2 Spoil = say the algorithm to those who want to discover it themselves (which is bad) (in this particular case). Of course there will be explanation later after the bounty has expired.

The random test generator doesn’t enforce A[0] = 0 like the question specifies.

Still pretty sure that I can get better score with algorithmic optimization. Need to try to be sure.

Well, out-timed (mostly because I'm lazy)

@user202729: Any ideas in the mean-time ? I don't see how the inner-loop could be avoided resp. replaced by code running in sub-linear time.

@politza AndersKaseorg's algorithm is much more sophiscated anyway, so reduce O(n^2 * k) to O(n * log(n) * k) won't help much. Although, I do have an idea now...

I may still be faster in practice, also simplicity has its own appeal.

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 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))));
}

Ruby, 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!
I don't think it's going to win, but I wanted to give it a try.

JavaScript (ES6) (Node.js), 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!
Run the same way as the other one.
JavaScript (ES6) (Node.js), 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!
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.

Consider the testcase K = 2, A = [0, 21, 31, 45, 49, 54]. The correct answer is 40, but your program outputs 51.

Even simpler: K = 2, A = [0, 4, 7, 9, 10]. Correct: 7, your answer: 8.

Okay It should be working now... It at least works for all provided cases.

Actually I also may have derived another algorithm that works better. I'm going to test the theory and post it in a bit.

Still not working... K = 2, A = [0, 1, 3, 4, 9]. Correct: 6, your answer: 7.

Last attempt at this, I have other projects to get to :/

K = 2, A = [0, 1, 4, 9]. Correct: 4, your answer: 6.

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]

If you increase the limit of step to 70, then your pretest score is 60.

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

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.

@ColeraSu May I ask what the deciding factor was in the score? Correctness / Time / Memory? I hope it was Time.

You are right, it was time.


text:
A bank for less Trustworthy Friends
Introduction
You have gotten a job as the minister of finance in your made-up country in your back yard. You have decided to make your own bank in your country for you and your less trustworthy friends. Since you don't trust your friends, you have decided to write a program to validate all transactions to stop your friends from overspending your made-up currency and ruining your economy.
Task
Given the starting balance and all transactions, filter out all transactions where someone tries to overspend and block anyone who tries to overspend (this includes trying to overspend to a closed account) from ever using your bank again by filtering out future transactions to or from his/her bank account.
Input/Output
Two lists A and B as input and a list C as output. A is the starting balance of each account with the format [["Alice", 5], ["Bob", 8], ["Charlie", 2], ...]. B is a list of transactions with the format [["Bob", "Alice", 3], ["Charlie", "Bob", 5], ...] where ["Bob", "Alice", 3] means that Bob wants to pay Alice 3 currency units. C should have the same format as B. A, B and C may be in any reasonable format.
Test Cases
A: [["Alice", 5], ["Bob", 2]]
B: [["Alice", "Bob", 5], ["Bob", "Alice" 7]]
C: [["Alice", "Bob", 5], ["Bob", "Alice" 7]]

A: [["A", 2], ["B", 3], ["C", 5]]
B: [["C", "A", 2], ["B", "C", 4], ["A", "B", 2]]
C: [["C", "A", 2]]

A: [["A", 2], ["B", 3]]
B: [["A", "B", 2], ["A", "B", 2]]
C: [["A", "B", 2]]

A: [["A", 4], ["B", 0]]
B: [["A", "B", 1], ["A", "B", 5], ["A", "B", 2]]
C: [["A", "B", 1]]

A: [["A", 2], ["B", 3], ["C", 4]]
B: [["A", "B", 3], ["C", "B", 4]]
C: [["C", "B", 4]]

A: [["A", 2], ["B", 3], ["C", 4]]
B: [["A", "B", 3], ["B", "A", 4], ["C", "B" 2]]
C: []

Scoring
This is code-golf, the shortest code in bytes in each language wins.

How strict is the IO format? Could A also be a dictionary, or a list of tuples?

@Laikoni Or even just a list of the form ["A", 2, "B", 3, "C", 5]?

Suggested test case: A: [["A", 2], ["B", 3], ["C", 4]], B: [["A", "B", 3], ["C", "B", 4]], C: [["C", "B", 4]] (a valid transaction following an invalid one).

What happens if someone tries to overspend, and the intended recipient has already overspent?

There's no comma in ["B" 3] in the second and third test cases

JavaScript (ES6), 91 88 79 bytes
Saved 8 bytes thanks to @NahuelFouilleul
Takes input in currying syntax (a)(b).
a=>b=>b.filter(([x,y,z])=>(a[x]+=z)<0&a[y]<0?a[y]-=z:0,a.map(([x,y])=>a[x]=~y))

Test cases

let f =

a=>b=>b.filter(([x,y,z])=>(a[x]+=z)<0&a[y]<0?a[y]-=z:0,a.map(([x,y])=>a[x]=~y))

console.log(JSON.stringify(f(
  [["Alice", 5], ["Bob", 2]]
)(
  [["Alice", "Bob", 5], ["Bob", "Alice", 7]]
)))

console.log(JSON.stringify(f(
  [["A", 2], ["B", 3], ["C", 5]]
)(
  [["C", "A", 2], ["B", "C", 4], ["A", "B", 2]]
)))

console.log(JSON.stringify(f(
  [["A", 2], ["B", 3]]
)(
  [["A", "B", 2], ["A", "B", 2]]
)))

console.log(JSON.stringify(f(
  [["A", 4], ["B", 0]]
)(
  [["A", "B", 1], ["A", "B", 5], ["A", "B", 2]]
)))

console.log(JSON.stringify(f(
  [["A", 2], ["B", 3], ["C", 4]]
)(
  [["A", "B", 3], ["C", "B", 4]]
)))

Beautified and commented
a => b =>                 // given the two lists a and b
  b.filter(([x, y, z]) => // for each (x = payer, y = payee, z = amount) in b:
    (a[x] += z) < 0 &     //   update the payer's account; if it's still valid
    a[y] < 0 ?            //   and the payee's account is also valid:
      a[y] -= z           //     update the payee's account
    :                     //   else:
      0,                  //     do nothing
    a.map(([x, y]) =>     //   initialization: for each (x = owner, y = amount) in a:
      a[x] = ~y           //     set up this account (>= 0: closed, -1: $0, -2: $1, etc.)
    )                     //   end of map()
  )                       // end of filter()

what about a=>b=>b.filter(([x,y,z])=>(a[x]-=z)>0&a[y]>0?a[y]+=z:0,a.map(([x,y])=>a[x]=y+1)) porting perl solution to javascript ?

@NahuelFouilleul Much better indeed. Thanks!

Perl 5, 72 + 2 (-ap) = 74 bytes
%h=@F;$_=<>;s/(\S+) (\S+) (\S+)/($h{$1}-=$3)<0||($h{$2}+=$3)<$3?"":$&/ge

try it online

Python 2, 103 bytes
A,B=input()
C=[]
for i in B:
 N,P,M=i
 if M>A[N]:A[N]=-1
 if A[N]>-1<A[P]:A[N]-=M;A[P]+=M;C+=i,
print C

Try it online!
-12 thanks to ovs.
Longer due to output format restrictions:

C should have the same format as B.

Otherwise I could've done this for 92 bytes:
A,B=input()
for(N,P,M)in B:
 if M>A[N]:A[N]=-1
 if A[N]>-1<A[P]:A[N]-=M;A[P]+=M;print(N,P,M)

103 bytes

@ovs wow, that's clever

Ruby, 57 bytes
->a,b{b.select{|(s,r,x)|a[r]+=x if[a[s]-=x,a[r]].min>-1}}

Try it online!
Takes input A as a Hash in the format {"A"=>2, "B"=>3}. Input B and output C are in the suggested format.
Explanation
->a,b{                      # lambda function taking arguments A and B
b.select{|(s,r,x)|              # select items in B that return truthy (s = sender, r = receiver, x = amount)
            a[s]-=x,                # subtract amount from sender
        if [         a[r]].min>-1   # check if the smaller of the balances is non-negative
                                    # (true if both values are non-negative)
a[r]+=x                             # if so, add to the receiver's balance
}                               # the select function returns truthy when the above if statement passes
}

C++, 193 bytes
Input A as std::map, B as std::list.
#import<bits/stdc++.h>
using s=std::string;struct p{s a,b;int c;};using t=std::list<p>;t f(std::map<s,int>A,t B){t C;for(p&i:B)(A[i.a]-=i.c)<0|A[i.b]<0?0:(C.push_back(i),A[i.b]+=i.c);return C;}

Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Append and erase
Given one line that consists of only letters, process as following:

You maintain a string that's empty at the beginning.
If the next input character is in the string, remove it from the string.
If the next input character isn't in the string, append it to the string.

Output the final state of the string.
You can safely assume the input consists at least one character (i.e. non-empty), but there's no guarantee that the output isn't empty.
Pseudocode (Feel free to golf this):
str = EMPTY
for each character ch in input
  if ch exists in str
    remove all ch from str
  else
    append ch to str
print str

The input matches the regular expression ^[A-Za-z]+$.
Sample test cases:
ABCDBCCBE -> ADCBE
ABCXYZCABXAYZ -> A
aAABBbAbbB -> aAbB
GG -> (empty)

The input can be given in any applicable way, but it must be treated as a string, and the same for output. The program should not exit with an error.
The shortest program in each language wins!
Extra (Optional): Please explain how your program works. Thank you.

May the line be empty?

@user202729 No. I changed a little (it does not invalidate any answer) so the input is never empty.

So why did you reject ais523's edit suggestion (link)?

Jelly, 3 bytes
œ^/

Try it online!
Full program.

Why is œ^/ not enough?

@JonathanAllan The program should not exit with an error.

the input is never empty Well, now it works.

Haskell, 44 42 bytes
foldl(#)""
s#x|z<-filter(/=x)s=z++[x|z==s]

Try it online! Edit: -2 bytes thanks to Zgarb!
Explanation:
The second line defines a function (#) which takes a string s and a character x and performs either the remove or append. This is achieved by filtering out every occurrence of x in s, resulting in the string z. If x does not occur in s, then z is equal to s and z++[x|z==s] yields the original string with x appended. Otherwise [x|z==s] yields the empty string and only the filtered string is returned.
foldl(#)"" is an anonymous function which takes a string and adds one character after the other the initially empty string "" with the function (#).

42 bytes by reusing the filter.

J, 21 19 bytes
#~~:&.|.(2|*)1#.=/~

How it works:
=/~ - makes a table of equality of the characters in the string:
   a =. 'ABCXYZCABXAYZ'
   ]b =: =/~ a
1 0 0 0 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 1 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 0 0 0 0 0 1
0 0 1 0 0 0 1 0 0 0 0 0 0
1 0 0 0 0 0 0 1 0 0 1 0 0
0 1 0 0 0 0 0 0 1 0 0 0 0
0 0 0 1 0 0 0 0 0 1 0 0 0
1 0 0 0 0 0 0 1 0 0 1 0 0
0 0 0 0 1 0 0 0 0 0 0 1 0
0 0 0 0 0 1 0 0 0 0 0 0 1

1#. - sum of each row by base 1 conversion (how many times the letter occurs)
   ]c =: 1#. b
3 2 2 2 2 2 2 3 2 2 3 2 2

~:&.| - reverse, then apply nub sieve (is the char unique) and reverse again. Thus I find the last occurrences of the characters in the string:
   ]d =. ~:&.|. a
0 0 0 0 0 0 1 0 1 1 1 1 1

* - multiplies the count by 1 for the last position of the character in the sring, by 0 otherwise, computed by the above ~:&.|
   ]e =. c * d
0 0 0 0 0 0 2 0 2 2 3 2 2

2| - modulo 2 (sets to 0 the positions of the chars that have even count):
   ]f =. 2| e
0 0 0 0 0 0 0 0 0 0 1 0 0

#~ - copy the right argument left arg. times (~ reverses the places of the args)
]f # a
A
Try it online!

Brainfuck, 95 bytes
,[<<<[[->+>>>+<<<<]>>>[-<+<->>]<<[[-]<]>[[-]>>[-]>[[-<+>]>]<<[<]<<]<<]<[->>>>[-]<<<]>>>>[->+<]>>[>]>>,]<<<[.<]

Try It Online
How It Works
, Gets first input
[ Starts loop
    <<< Go to start of string
    [ Loop over the string
        [->+>>>+<<<<] Duplicates the current char of the string
        >>>[-<+<->>] Duplicates and subtracts the inputted char from the duplicate of the string char
        <<[[-]<] If the char is different to the input, remove the difference
        > If the char is the same
        [
            [-]>>[-]>[[-<+>]>]<<[<]<< Remove the char from the string and sets the inputted char to 0
        ]
        << Moves to the next char of the string
    ]
    >>>[->+<] adds the inputted char to the string
    >>[>]>>, gets the next input
]
<<<[.<] prints the string

Haskell, 47 bytes
Another one bytes the dust thanks to Bruce Forte.
import Data.List
foldl1(\x y->union(x\\y)$y\\x)

Try it online!
Takes a list of Strings.
Symmetric difference is annoying...

++ saves 2 bytes over union with this method.

MATL, 6 bytes
vi"@X~

Doesn't work in the TIO environment, but works fine on the MATLAB implementation, and thanks to a fresh patch, you may try it on MATL Online
X~ equals setxor, or symmetric difference, which does exactly what the challenge asks. The rest is just looping over the input i"@ and starting with an empty string by concatenating the entire stack which is empty at the start (thanks Luis Mendo).

Retina, 16 bytes
+1`(.)(.*?)\1
$2

Try it online!

K (ngn/k), 21 9 bytes
|&2!#'=|:

Try it online!
If a character appears an even number of times in the string, it won't be present in the output. If it appears an odd number of times, only its last instance will remain.

#'=|: count the number of times each distinct character occurs in the string (reversing the order)
|&2! filter down to where the character appears an odd number of times, then reverse

Python 2, 56 bytes
-2 bytes thanks to xnor. -3 bytes thanks to ovs.
lambda s:reduce(lambda a,c:a.replace(c,'')+c[c in a:],s)

Try it online!
Literally just golfed the pseudocode. :P

Save 2 bytes: s=(s+c).replace(c,c[c in s:]).

@xnor That's some basic golfing executed very cleverly. Thanks!

-1 byte : s=s.replace(c,'')+c[c in s:]

56 bytes using reduce

q, 38 bytes
""{$[y in x;except;,][x;y]}/

R, 84 bytes
y=el(strsplit(scan(,""),""));cat(unique(y[colSums(outer(y,y,"=="))%%2>0],,T),sep="")

Try it online!
Another solution, but there are better R answers here.
R, 88 bytes
z=table(y<-el(strsplit(scan(,""),"")));cat(setdiff(unique(y,,T),names(z[!z%%2])),sep="")

Try it online!
Thanks to Giuseppe for -7 bytes!
There is a shorter answer by duckmayr.

scan(,"") read input from stdin.
y<-el(strsplit(scan(,""),"")) split input by characters and save as y.
z=table(y<-el(strsplit(scan(,""),""))) compute frequencies of each character and save resulting table as z;
unique(y,,T) take unique characters from the right side.
names(z[!z%%2]) select only even counts and extract names.
setdiff(unique(y,,T),names(z[!z%%2])) remove characters with even count.
cat(setdiff(unique(y,,T),names(z[!z%%2])),sep="") print the output.

The reason for your error is that el() comes from the methods package, which while typically loaded by default, is not by TIO (discussed in my answer below)

why are you using rev(unique(rev(y)))? Wouldn't just unique(y) work? ooohhh wait I see, you want the unique characters from right to left. In that case unique(y,,T) (setting fromLast=T) will be 88 bytes.

R, 92 84 77 bytes
for(i in el(strsplit(scan(,y<-''),y)))y=c(y[y!=i],if(!i%in%y)i);cat(y,sep='')

Try it online!
-15 bytes thanks to djhurio
Explanation
djhurio provided an excellent R answer avoiding a for loop -- as R programmers instinctively do as a rule (myself included). Here's an R answer that utilizes a for loop (and saves a few bytes in the process).

x=scan(,''); -- assign the input into the variable x
y=''; -- create an empty string in a variable called y
for(i in el(strsplit(x,''))) -- for every character i in x
y=c(y[y!=i],if(!i%in%y)i) -- assign to y every element of y that is not equal to i, appending i if i was not already in y
cat(y,sep='') -- print the elements of y with no space between them

Note
If you click the TIO link above, you'll find in the header library(methods); this is to deal with the error djhurio experienced regarding the el() function -- the function is provided by the methods package, which in any version of R I've used, is loaded by default, but for whatever reason isn't by TIO. If library(methods) is removed from the header and unlist is substituted for el, I gain four bytes, but so would djhurio, putting our byte counts at 96 88 and 99 respectively.

Nice one. Never thought for loop will be shorter. You can make it even more shorter by omitting else statement for(i in el(strsplit(scan(,y<-''),y)))y=c(y[y!=i],if(!i%in%y)i);cat(y,sep='').

@djhurio -- I know, it's almost never the case that in R a for loop will help with anything. Regarding your suggestion: Great idea! The suggestion is now incorporated in the answer.

why don't you take the 79 bytes answer from my comment?

@djhurio -- fair enough; I was too busy looking at the difference introduced by omitted the else statement I didn't see how you had changed the beginning. Editing now. Great work!

@djhurio @duckmayr there's a 73 byte solution that is basically taking this solution and using a slightly different approach to extracting characters. I didn't really feel like posting it as a separate answer. Also note that ...[[1]] is longer than el(...) but shorter than unlist(...), provided that ... is a list of length 1.

scratch that, I found a 70 bye answer since 0 is the nul character and gets converted to the empty string.

@Giuseppe, great. You should make at as a new answer.

JavaScript (ES6), 60 bytes
s=>[...s].map(c=>s=s.match(c)?s.split(c).join``:s+c,s='')&&s

Test cases

let f =

s=>[...s].map(c=>s=s.match(c)?s.split(c).join``:s+c,s='')&&s

console.log(f("ABCDBCCBE"))     // -> ADCBE
console.log(f("ABCXYZCABXAYZ")) // -> A
console.log(f("aAABBbAbbB"))    // -> aAbB
console.log(f("GG"))            // -> (empty)

I ported @MartinEnder's Retina answer and it was only 45 bytes...

APL+WIN, 19 bytes
Logic similar to Galen's J solution.
(2|+⌿⌽<\⌽c∘.=c)/c←⎕

Wolfram Language (Mathematica), 36 bytes
#//.{a___,x_,b___,x_,c___}:>{a,b,c}&

Try it online!
Takes input and output as a list of characters.
How it works
Uses //. (alias ReplaceRepeated) to find two repeated characters and delete both, until no more repeated characters exist. If the character occurs more than twice, Mathematica will always delete the first two occurrences. So if a character occurs an odd number of times, its last instance will always be the one to survive.

Perl 5, 28 + 2 (-pF) = 30 bytes
$\=~s/$_//g||($\.=$_)for@F}{

Try it online

Prolog 81 byte
a([],O,O).
a([I|J],K,O):-delete(K,I,F),(K=F->append(K,[I],M),a(J,M,O);a(J,F,O)).

Non-obfuscated version:
append_and_eraze([], Output, Output).
append_and_eraze([I | Input], Interim, Output) :-
    delete(Interim, I, Filtered),
    ( Interim = Filtered ->
      append(Interim, [I], Interim1),
      append_and_eraze(Input, Interim1, Output)
    ;
    append_and_eraze(Input, Filtered, Output)
    ).

delete/3 ensures that its third argument unifies with its first argument, with all instances of second argument removed from it.
If those turn out to be the same, we append the element (it wasn't removed).
append/3 as per its name, appends an element to list.
We recur on the elements of the input until we hit the [] (empty list), at which point the intermediate result will unify with desired result.

Test:
?- append_and_eraze(`ABCDBCCBE`, [], X), string_codes(Y, X).
X = [65, 68, 67, 66, 69],
Y = "ADCBE".

?- append_and_eraze(`ABCXYZCABXAYZ`, [], X), string_codes(Y, X).
X = [65],
Y = "A".

?- append_and_eraze(`aAABBbAbbB`, [], X), string_codes(Y, X).
X = [97, 65, 98, 66],
Y = "aAbB".

?- append_and_eraze(`GG`, [], X), string_codes(Y, X).
X = [],
Y = "".

Some Prologs treat strings in double quotes as lists, SWI can be configured to do the same, but for the sake of simplicity, I used string_codes/2 to format output nicely.

Japt -h, 15 bytes
;£A=øX ?AkX:ApX

Try it online!

14 bytes?

@Shaggy That won't work because S.k isn't case sensitive. The workaround would be 15 bytes: https://tio.run/##y0osKPlf@P/Q4gDbwzsiFOwDsiMMrQK0I/7/V0p0dHRySnJMSlLi4tLNAAA

Scala, 75..64 49 bytes
-22 bytes thanks to user!
_./:("")((?,y)=>if(?toSet y)?filter(y!=)else? +y)

Try it online!

Try using /: (foldLeft) here, it may save some bytes (I’m on mobile, so I can’t try it out right now)

You don't need to print, just return directly: 49 bytes. Also, I think toSet works instead of contains

REXX, 102 bytes
a=arg(1)
s=''
do while a>''
  b=right(a,1)
  if countstr(b,a)//2 then s=b||s
  a=changestr(b,a,'')
  end
say s

Try it online!
How it works: Take the rightmost letter, see if the number of occurrences is even or odd (which also doubles as a truth value) and if odd, add it to the output string. Then remove all occurrences of the letter from the input string. Repeat until input is depleted.

Perl 5, 22 + 1 (-p) = 23 bytes
s/(.)(.*?)\1/$2/&&redo

Try it online!

Java 8, 93 bytes
A lambda from String to String. Just an implementation of the pseudocode in the question.
s->{String o="";for(char c:s.toCharArray())o=o.indexOf(c)<0?o+c:o.replace(c+"","");return o;}

Try It Online
Java 8, 182 bytes
Here's another lambda of the same type that uses streams! It's probably more efficient.
s->s.join("",s.chars().mapToObj(c->(char)c+"").filter(c->s.replaceAll("[^"+c+"]","").length()%2>0).distinct().sorted((c,d)->s.lastIndexOf(c)-s.lastIndexOf(d)).toArray(String[]::new))

Try It Online
Ungolfed
s ->
    s.join(
        "",
        s.chars()
            .mapToObj(c -> (char) c + "")
            .filter(c -> s.replaceAll("[^" + c + "]", "").length() % 2 < 0)
            .distinct()
            .sorted((c, d) -> s.lastIndexOf(c) - s.lastIndexOf(d))
            .toArray(String[]::new)
    )

Alice, 9 bytes
/X&@
\io/

Try it online!
Explanation
Basically a port of Erik's answer. Apart from a bit of IP redirection the code is really just:
i&Xo@

which does:
i   Read all input.
&X  Fold symmetric multiset difference over the input.
o   Output the result.
@   Terminate.

Ruby, 53 bytes
->s{s.reverse.uniq.select{|c|s.count(c)%2>0}.reverse}

Try it online!
Input and output are both an array of chars. Test code calls .chars and .join for convenience.
Explanation
Uses the fact that the letters in the resulting string appear an odd number of times and in the order from right to left.
->s{                # lambda function taking char-array argument
    s.reverse           # reverse the input
    .uniq               # get unique characters
    .select{|c|         # select only those which...
        s.count(c)%2>0      # appear in the input array an odd number of times
    }.reverse           # reverse back and return
}

APL (Dyalog), 16 bytes
{(,⍨~∩)/⍣(≢⍵)⊖⍵}

Try it online!
If errors were allowed, this would've been 9 bytes:
(,⍨~∩)/∘⊖

What do you mean by errors?

@FrownyFrog The 9-byte version would throw a DOMAIN ERROR if the string is empty, since (,⍨~∩) doesn't have a predefined identity element.

Pyth, 15 bytes
Vz?:kN)=-kN=+kN

Try it online!

Pyth, 13 bytes
{_xD_Qf%/QT2Q

Takes in input as list of characters. Test it out!
      f     Q            (f)ilter input (Q)
        /QT              On how many times (/) each character (T) appears in the
                           input (Q)
       %   2             Only allow odd numbers of occurences (when x % 2 = 1)
 _xD_Q                   Sort (D) descending (the first _) by the location (x) of
                           the last (the second _) inde(x) of the target character
                           in the input (Q)
{                        Remove duplicates

10 bytes, but returns 0 instead of an empty string.

Röda, 34 bytes
{a=[]a-=_ if[_1 in a]else a+=_1;a}

Try it online!
This is a direct translation of the pseudocode. It treats input and output as streams of characters.
Explanation:
{                    /* Anonymous function                   */
    a=[]             /* initialize a                         */
                     /* For each character _1 in the stream: */
    a-=_ if[_1 in a] /*  Remove it from a if a contains it   */
    else a+=_1;      /*  Otherwise append it to a            */
    a                /* Push characters in a to the stream   */
}

Python 3, 73 bytes
Not the shortest, but I like this approach.
lambda s:''.join(c*(s.count(c)%2)*(i==s.rfind(c))for i,c in enumerate(s))

Try it online!
Loops through the string, keeping only those characters where:

(s.count(c)%2) == 0 - The character appears an even number of times.
(i==s.rfind(c)) - The current index is the last appearance of the character in question.

R, 70 bytes
function(s){for(i in utf8ToInt(s))F=c(F[F!=i],i*!i%in%F);intToUtf8(F)}

Try it online!
I was encouraged by djhurio to post this solution; djhurio's answer can be found here.
This uses the same idea as duckmayr's answer, but it leverages a numeric approach by converting the string to its codepoints rather than splitting it into characters, and is a function rather than a full program so it can return the new string rather than printing to stdout.
function(s) {
 for(i in utf8ToInt(s))           # convert string to codepoints and iterate over it
  F=c(F[F!=i],                    # remove duplicates and append
      i*!i%in%F)                  # 0 if in F, i otherwise
 intToUtf8(F)                     # collapse from codepoints to string
}

One important observation is that F is initialized to FALSE or 0 and utf8ToInt(0)=="", so this will succeed for the empty string as well as correctly collapsing the codepoints.

PHP, 71+1 bytes
while(~$c=$argn[$i++])$s=strstr($s,$c)?strtr($s,[$c=>""]):$s.$c;echo$s;

Run as pipe with -nR or try it online.

Python 3.6, 69 bytes
lambda a:"".join({c:1 for c in a[::-1] if a.count(c)%2}.keys())[::-1]

Try it online!
Dict insertion order is preserved in Python 3.6 .

SNOBOL4 (CSNOBOL4), 97 95 bytes
	S =INPUT
N	S LEN(1) . C REM . S :F(O)
	O C :S(R)
	O =O C :(N)
R	O C =:S(R)F(N)
O	OUTPUT =O
END

Try it online!
	S =INPUT			;* read input
N	S LEN(1) . C REM . S :F(O)	;* take the first character of S and assign it to C,
					;* assign the remainder to S, and if S has no characters left, goto O
	O C :S(R)			;* if C matches anything in O, goto R, otherwise go to next line
	O =O C :(N)			;* append C to O and goto N
R	O C =:S(R)F(N)			;* as long as C matches O, replace it with ''
					;* (unassigned variables default to the null string)
					;* then goto N once it fails to match
O	OUTPUT =O			;* output the string
END					;* terminate the program

Julia 0.6, 49 bytes
~x=foldl((s,c)->in(c,s)?replace(s,c,""):s*c,"",x)

Try it online!
Algorithm from the pseudocode. This does not work like this in tio.run  because concatenation of a string with a char using * is not defined. It does work in JuliaPro 0.6.1.1 however, where this is defined from the future™ (0.7 dev).

C (gcc), 95 94 bytes
char*f,*g,c[256];F(char*s){for(f=s;*f;++c[*f++]);for(g=f;f>=s;--f)c[*f]&1?c[*g--=*f]=0:0;++g;}

Try it online!
char *F(char *src);

The input is a null terminated string. It must be writeable.
The output is a pointer to the middle of the source string containing the filtered string (done with the return hack). It will also be null terminated.
Uses a similar approach to djhurio's second answer and coltim's answer, where I count the characters, then select only the last characters that appear once.
It is the only viable option, you can't just "remove" a character in C, and there are no fancy builtins that do anything close to what the other algorithms do.
However, unlike those two, I do everything manually because it is torture fun, and I modify the string in place without reversing it.
I initially tried doing something in C++ with <algorithm>, but std::remove_if moves forwards, meaning we would have to std::reverse twice.
Ungolfed version with comments:
char *append_and_erase(char *src)
{
    // Temp variables
    char *f, *g;
    // Buffer to hold our character count.
    char counts[256] = { 0 };

    // Count the occurrences of each character.
    for (f = src; *f != '\0'; f++)
         ++counts[*f];

    // Go backwards in the string, writing all the characters that appeared an
    // odd number of times, and skipping the ones that repeat.
    //
    // It is basically a backwards std::remove_if.
    //
    // g will point to the start of the trimmed string minus one.
    // It will look like this:
    //    garbageABCDEFG\0
    //    ^src  ^g
    // g will be off by one, so we need to increment it before we are done.
    for (g = f; f >= src; --f) {
        if (counts[*f] % 2 != 0) {
           *g-- = *f;
           // Clear the count so we don't have duplicates
           counts[*f] = 0;
        }
    }
    // More logical version:
    //
    //    f = src;
    //    g++;
    //    // strcpy but guaranteed to be forwards
    //    while ((*f++ = *g++) != '\0');
    //
    // Golf version:
    // Increment g and return it (we use the return hack in the golf)
    return g + 1;
}

Thanks to ceilingcat for the -1 byte using a ternary.

Thanks. I was so frustrated with operator precedence when trying to do && that I forgot about ternaries. ♂

Thunno 2 t, 2 bytes
Ʋḍ

Try it online!
Port of Erik the Outgolfer's Jelly answer.
Explanation
Ʋḍ  # Implicit input
Ʋ   # Reduce the input by:
 ḍ  #  Symmetric set difference
    # Implicit output

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Swap the Endianness
As most of you  probably know, (byte-addressable) hardware memories can be divided into two categories - little-endian and big-endian. In little-endian memories the bytes are numbered starting with 0 at the little (least significant) end and in big-endian ones the other way round.
Fun fact: These terms are based on Jonathan Swift's book Gulliver's Travels where the Lilliputian king ordered his citizens to break their eggs on the little end (thus the little-endians) and the rebels would break theirs on the big end.
How swapping works
Suppose we have an unsigned integer (32bit) 12648430 in memory, in a big-endian machine that might look as follows:
  addr: 0  1  2  3
memory: 00 C0 FF EE

By inverting the byte-order we get the hexadecimal integer 0xEEFFC000 which is 4009738240 in decimal.
Your task
Write a program/function that receives an unsigned 32bit integer in decimal  and outputs the resulting integer when swapping the endianness as described above.
Rules

Input will always be in the range 0 to 4294967295
Output can be printed to STDOUT (trailing newlines/spaces are fine) or returned
Input and output are in decimal
Behavior on invalid input is left undefined

Test cases
0 -> 0
1 -> 16777216
42 -> 704643072
128 -> 2147483648
12648430 -> 4009738240
16885952 -> 3232235777
704643072 -> 42
3735928559 -> 4022250974
4009738240 -> 12648430
4026531839 -> 4294967279
4294967295 -> 4294967295

For a function answer, does "input and output are in decimal" mean either a string of digit characters or array of digit values is required?  Or can a function answer use its language's natural integer value representation, which in most cases has absolutely nothing to do with "decimal"?

@aschepler The language's integer value, eg. 42 is given in decimal but technically it's in binary in C for example. You can of course type 0x2a, what I wanted to prevent is taking input as a string like "2a" or the like.

Related (as this challenge is just making sure to pad to 32 bits first)

x86_32 machine language, 3 bytes
endian_swap:        # to be called with PASCAL REGISTER calling convention
0f c8    bswap eax
c3       ret

This is a bit of a cheat. The Pascal register calling convention (see Wikipedia) is a bit like __fastcall, except it passes the first parameter in eax, and eax also contains the return value. It's also callee-cleanup, but since we don't use the stack for anything other than the return pointer we don't need to do anything. This allows us to avoid a mov or xchg and just use bswap directly.

May want to note that bswap requires an 80486 or higher :)

@ceilingcat Very true, although I'm sure that's implicitly the case for many other solutions here due to compiler or toolchain restrictions!

x86_64 machine language Linux, 5 4 bytes
0:       0f cf                   bswap  %edi
2:       97                      xchg   %eax,%edi
3:       c3                      retq

Thanks to @peter ferrie for -1.
Try it online!

that's not a decimal return value.  I don't think that counts.  Besides, you could xchg edi,eax for 4 bytes.

@peterferrie Wow I was just browsing your website reading about PE headers!

C (gcc) , 20, 29 17 bytes
@hvd's suggestion.
__builtin_bswap32

Try it online!
Old answer;
#include<byteswap.h>
bswap_32

include should be import.

Japt, 10 14 bytes
sG ùT8 ò w ¬nG

Try it

Explanation
Convert input integer to a base-16 string (sG), use 0 to pad the start to length 8 (ùT8), split to an array of 2 character strings (ò), reverse (w), rejoin to a string (¬) and convert back to base-10 (nG).

You know, what might be a handy feature is to have more functions like y that, when given a function a function, apply their normal transformation, run the function, and then invert the transformation. In this case I think that would allow it to be shortened to sG_ò w ¬ for 8 bytes. Or if ò did that too, it could even be sG_ò2_w for 7...

@ETHproductions I support it; the under-&. adverb in J does this and it's sometimes really helpful in golfing. Coding in all the inversions might be tedious, though.

@ETHproductions: the more "overloading", the better :) I wrote this up while pulling pints and originally had sG_òw..., could not, for the life of me, figure out why it wouldn't work! I realised my mistake(s) eventually!

Doesn't seem to work for input less than 2<<24...

Thanks, @Neil; will get that fixed later on. Looks like it'll cost me 4 bytes.

Jelly, 10 bytes
⁴4*+b⁹ḊṚḅ⁹

Try it online!

Alternative 10 bytes I can find: d⁹²¤d⁹FUḅ⁹

C#, 70 68 bytes
This is probably not optimal.
68:
Func<uint,uint>f=n=>((n=n>>16|n<<16)&0xFF00FF00)>>8|(n&0xFF00FF)<<8;

70:
uint e(uint n){n=n>>16|n<<16;return(n&0xFF00FF00)>>8|(n&0xFF00FF)<<8;}
Try it online!

You can move the assignment into the return expression and then use expression-bodied member syntax: uint e(uint n)=>((n=n>>16|n<<16)&0xFF00FF00)>>8|(n&0xFF00FF)<<8; for 64 bytes.

@hvd That's not showing as valid expression-bodied syntax for me. I was however able to use the shift rearrangement trick to shave 2 bytes off.

I copied and pasted from my comment into your TIO link to make sure there were no typos or anything like that and exactly the way it is in my comment, it works: TIO link

I noticed 0xFF00FF00 is the complement of 0xFF00FF and wonder if you can take advantage of that? But declaring it a variable takes too many characters

Oh! Good to check the constants indeed: you can use 0xFF00FF twice by >>ing before &ing, and you can then shorten 0xFF00FF to ~0u/257: uint e(uint n)=>((n=n>>16|n<<16)>>8&~0u/257)|(n&~0u/257)<<8; for 60. TIO link

Or 58 after removing the redundant parentheses: TIO link.

@hvd Nice trick with the /257. You should post a C# answer since your optimisations are way better than mine. Regarding syntax issues, I was testing in LinqPad so maybe they're a bit behind on language support regarding expression-bodied members outside of variable expression assignments.

Python 2, 44 bytes
f=lambda x,i=3:x and(x%256)<<8*i|f(x>>8,i-1)

Try it online!

You can save a byte recursing with i*8 rather than i, starting from i=24.

And the parens around the x%256 aren't necessary.

APL+WIN 14 bytes
256⊥⌽(4⍴256)⊤⎕

Explanation
⎕ prompt for screen input
(4⍴256)⊤ 4 byte representation in base 256
⌽ reverse bytes
256⊥ bytes from base 256 to integer

Would 256⊥⌽⎕⊤⍨4⍴256 work for -1 byte?

The ⍨ operator is not available in APL+WIN so the answer is no but it could well be yes for Dyalog APL

Wolfram Language (Mathematica), 24 bytes
IntegerReverse[#,256,4]&

Try it online!
Reverses the input interpreted as an integer in base 256 with 4 digits.

05AB1E, 12 10 bytes
3F₁‰R`})₁β

Try it online! Explanation:
  ₁         Integer constant 256
   ‰        [Div, Mod]
    R       Reverse
     `      Flatten to stack
3F    }     Repeat 3 times
       )    Collect results
        ₁β  Convert from base 256

This doesn't seem to be a valid solution. The "padding" you do is actually repeating the list of bytes to length 4.

@EriktheOutgolfer Bah, I wish the documentation would actually say that...

MATL, 12 10 bytes
7Y%1Z%P7Z%

Try it online! Or verify all test cases.
Explanation
        % Implicitly input a number, read as a double
7Y%     % Cast to uint32
1Z%     % Convert to uint8 without changing underlying data. The result is
        % an array of four uint8 numbers, each corresponding to a byte of
        % the original number's representation
P       % Flip array
7Z%     % Convert back to uint32 without changing underlying data. The array
        % of four uint8 numbers is interpreted as one uint32 number.
        % Implicitly display

05AB1E, 9 bytes
žJ+₁в¦R₁β

Try it online!
-1 thanks to Neil.
Port of my Jelly answer.

JavaScript (ES6), 45 43 bytes
f=(n,p=0,t=4)=>t?f(n>>>8,p*256+n%256,t-1):p

Starting with t=0 saves 2 bytes: f=(n,p=t=0)=>t++<4?f(n>>>8,p*256+n%256):p

PPC Assembly (32-bit), 8 bytes
endian_swap:    # WORD endian_swap(WORD)
7c 60 1c 2c     LWBRX 3,0,3
4e 80 00 20     BLR

How this works:

PPC calling convention puts the first 32-bit word parameter into SP+24, and shadows that address into GPR3.
LWBRX takes load GPR3 (third operand) and zero-extends it (second operand) into EA, then reads 4 bytes in reverse order and stores it into GPR3 (first operand).
GPR3 holds the return value.
BLR returns from the function (branches to the address in the LR register)

Unfortunately there aren't any online PPC assembly emulators that I could find to demonstrate. Sorry!

Befunge, 62 61 or 49 bytes
0&0v!p22:/3g22/*:*82\+%*:*82+<
@.$_:28*:*%00p\28*:**00g28*:*^

Try it online!
This is using standard Befunge on the reference interpreter, and we thus need to account for the fact that memory cells are 8-bit signed, and correct for possible signed overflow.
On implementations with unsigned memory cells (e.g. PyFunge), or where the range is greater than 8 bits (e.g. FBBI), we can get away without those checks, saving 12 bytes.
0&0v!p22:/3g22/*:*82\+g<
@.$_:28*:*%00p\28*:**00^

Try FBBI online!
Try PyFunge online!
Although note that PyFunge has a bug processing integer input, so when testing on TIO you need to follow the number in the input field with a space or line break.

C, 50 bytes
#define f(i) (i>>24|i>>8&65280|(i&65280)<<8|i<<24)

Try it online!
To be more portable, I didn't want to use any functions that aren't in ANSI C. :-)
Like @hvd, I also cribbed Polynomial's answer. Due to C's operator precedence, I had to add parentheses around the third term.

Octave, 10 bytes
@swapbytes

Try it online!
This may be the first time that Octave has the exact same score as its golfing derivative, MATL. Of course, in this case, it's Octave that has the built-in, rather than MATL, making it a lot easier.
Defines a handle to the built-in swapbytes, which takes any data type, swaps the endianness and outputs the result. In this case, the input is a 32-bit unsigned integer.

C#,  44  36 bytes
n=>n>>24|n>>8&65280|n&65280<<8|n<<24

Try it online!
This was originally based on Polynomial's C# answer, who suggested I post a new answer with my improvements on it, but the approach taken in Arnauld's JavaScript answer turned out to be even shorter in C#.

R, 86 bytes

I thought there was already an answer (or two) in R  for this question, but I must have been mistaken or they had the same issues that I had with R not doing signed ints.  That issue took out any builtins that could have helped. I tried the 256 base conversion, but it ended up being to long, but I think there is still room for someone smarter than me to do that.  Then I ended up with the following which it a base 2 conversion swapping the order in a recursive function.
f=function(x,y=0,i=31)'if'(i+1,f(x-(2^i*z),y+(2^((3-i%/%8)*8+i%%8)*(z=2^i<=x)),i-1),y)

Try it online!
f=function(x,y=0,i=31)       # set up the function and initial values
  'if'(i+1,                  # test for i >= 0
    f(                       # recursively call the function
      x-(2^i*z),             # remove 2^i from x when 2^i <= x
      y+(2^                  # add to y 2 to the power of
        ((3-i%/%8)*8+i%%8)   # calc to swap the order of the bytes
        *(z=2^i<=x)),        # when 2^i <= x
      i-1),                  # decrement i
   y)                        # return y

you were right about base 256 being shorter!

@Giuseppe, you are going to put hat one up aren't you

JavaScript (ES6), 51 45 bytes
Saved 6 bytes with @Neil's help
n=>(n>>>24|n>>8&65280|(n&65280)<<8|n<<24)>>>0

Test cases

let f=

n=>(n>>>24|n>>8&65280|(n&65280)<<8|n<<24)>>>0

console.log(f(0         )) // -> 0
console.log(f(1         )) // -> 16777216
console.log(f(42        )) // -> 704643072
console.log(f(128       )) // -> 2147483648
console.log(f(16885952  )) // -> 3232235777
console.log(f(704643072 )) // -> 42
console.log(f(3735928559)) // -> 4022250974
console.log(f(4009738240)) // -> 12648430
console.log(f(4026531839)) // -> 4294967279
console.log(f(4294967295)) // -> 4294967295

Nice, best I could get with recursion was f=(n,p=0,t=4)=>t?f(n/256|0,p*256+n%256,t-1):p.

@ETHproductions ...that's shorter?

@ETHproductions That's definitely shorter. You should post it.

46 bytes: n=>(n>>>24|n>>8&65280|n<<8&16711680|n<<24)>>>0

68 bytes using builtins: n=>(b=new DataView(new ArrayBuffer(4))).getUint32(b.setInt32(0,n,1))

@Neil D'oh. That (n&255)<<24 was silly indeed... Thanks!

Wait what, I counted 55 bytes on my version...

This answer can be trivially modified to work for C#, beating what I had come up with. I think it'd be cheating to incorporate that into my answer.

@hvd No worries. You can either add it as an alternate version or replace the existing one entirely. Up to you!

@Neil You can actually do it in 54: n=>new DataView(Int32Array.of([n]).buffer).getUint32()

@Pandacoder No, that converts from platform byte order to big-endian, so it will fail when the platform byte order is big-endian.

@Neil I'm aware, I just don't know of any big endian platforms with JS (so it's a caveat — but since it's not the shortest code it doesn't count).

Excel VBA, 103 92 Bytes
Anonymous VBE immediate window function that takes input from range [A1] converts to hex, reverses bytes, and outputs to the VBE immediate window
h=[Right(Rept(0,8)&Dec2Hex(A1),8)]:For i=0To 3:s=s+Mid(h,7-2*i,2):Next:[B1]=s:?[Hex2Dec(B1)]

Can I test this somewhere? Could you add an online interpreter, please?

@BruceForte No, unfortunately there are no online interpretters for any of the variants of VBA, however, if you have a copy of Excel on your computer, you can access the VBE by pressing Alt + F11, and then the immediate window by pressing Ctrl + G. For this anonymous function you would then paste your input into cell A1 and the code above into the immediate window and press enter

Oh - and sometimes VBA is a bit funky (and the Mac version is imperically worse than the windows version) so this, and unless otherwise stated all, VBA solutions assume the default 32-Bit Windows version

J, 16 bytes
|.&.((4#256)#:])

Try it online!
Working on shortening the right-hand expression. I think I can shave off a few bytes by making this work with a beta J version. I swear I saw on here that you can end a train with a noun in a new beta version...
Explanation
|.&.((4#256)#:])
    ((4#256)#:])  Convert to 4 two-byte blocks
            #:      Debase to
      4#256         4 digits base 256
  &.              Apply right function, left function, then inverse of right
|.                Reverse digits

Convert to 4 digits base 256, reverse the digits, then convert back to decimal. Basically, perform the algorithm that is provided in the OP. This is perhaps the one time where it's helpful that J's mixed base conversion requires you to specify the number of digits, although it would be 2 fewer bytes if I could end the train in a noun ((#:~4#256) instead).

CP-1610 assembly, 6 DECLEs = 8 bytes
This code is intended to be run on an Intellivision.
A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This function is 6 DECLEs long, starting at $480C and ending at $4811.
The CP-1610 has 16-bit registers, so we're using two of them (R0 and R1) to store a 32-bit value.
                               ROMW  10           ; use 10-bit ROM

                               ORG   $4800        ; start program at address $4800

                               ;; example call
4800  0001                     SDBD               ; load 0xDEAD into R0
4801  02B8 00AD 00DE           MVII  #$DEAD, R0
4804  0001                     SDBD               ; load 0xBEEF into R1
4805  02B9 00EF 00BE           MVII  #$BEEF, R1

4808  0004 0148 000C           CALL  swap32       ; call our function

480B  0017                     DECR  PC           ; loop forever

                               ;; swap32 function
                       swap32  PROC

480C  0040                     SWAP  R0           ; 16-bit SWAP of R0
480D  0041                     SWAP  R1           ; 16-bit SWAP of R1

480E  01C1                     XORR  R0, R1       ; exchange R0 and R1
480F  01C8                     XORR  R1, R0       ; using 3 consecutive eXclusive OR
4810  01C1                     XORR  R0, R1

4811  00AF                     JR    R5           ; return

                               ENDP

Execution dump
 R0   R1   R2   R3   R4   R5   R6   R7    CPU flags  instruction
 ------------------------------------------------------------------
 0000 4800 0000 0000 01FE 1041 02F1 4800  ------iq   SDBD
 0000 4800 0000 0000 01FE 1041 02F1 4801  -----D-q   MVII #$DEAD,R0
 DEAD 4800 0000 0000 01FE 1041 02F1 4804  ------iq   SDBD
 DEAD 4800 0000 0000 01FE 1041 02F1 4805  -----D-q   MVII #$BEEF,R1
[DEAD BEEF]0000 0000 01FE 1041 02F1 4808  ------iq   JSR  R5,$480C

 DEAD BEEF 0000 0000 01FE 480B 02F1 480C  ------iq   SWAP R0
 ADDE BEEF 0000 0000 01FE 480B 02F1 480D  S------q   SWAP R1
 ADDE EFBE 0000 0000 01FE 480B 02F1 480E  S------q   XORR R0,R1
 ADDE 4260 0000 0000 01FE 480B 02F1 480F  ------iq   XORR R1,R0
 EFBE 4260 0000 0000 01FE 480B 02F1 4810  S-----iq   XORR R0,R1
[EFBE ADDE]0000 0000 01FE 480B 02F1 4811  S-----iq   MOVR R5,R7

 EFBE ADDE 0000 0000 01FE 480B 02F1 480B  ------iq   DECR R7

Why is this 7.5 bytes? I think it should be 8 bytes.

@EriktheOutgolfer Fair enough. Updated accordingly.

@EriktheOutgolfer Because 60 bits equals 7.5 bytes?

@JeppeStigNielsen That's true, but a file can never be 7.5 bytes long, it will be pre- or post-padded with 0s.

@EriktheOutgolfer Technically, this could really be stored inside a 10-bit ROM. Here is an example spec sheet. (Today, we're using 16-bit ROM for Intellivision homebrew games, but back in the day, memory chips were so expensive that using 10-bit was a real money saver.)

@Arnauld Well, you can sure claim 7.5 bytes. You just need to be able to use it for this purpose as well. ;-)

R, 41 bytes
function(n)n%/%256^(0:3)%%256%*%256^(3:0)

Try it online!
Verify all test cases!
Uses a base-256 conversion as MickyT suggested here. R does not have unsigned 32-bit integers, nor does it have 64-bit integers. This prevents us from using bitwise operations but this approach (and likely MickyT's) is probably still shorter since R's bitwise operators are quite verbose.
Utilizes number 4 of this tip, taking into account that we're never getting a number as large as 256^4.
n%/%256^(0:3)%%256 extracts the bytes, and %*%, the matrix product, is the dot product in this situation, with 256^(3:0) effecting the reversed order of bytes. %*% will return a 1x1 matrix containing the endian-reversed value.

ARM machine language Linux, 8 bytes
0:       e6bf0f30       rev     r0, r0
4:       e12fff1e       bx      lr

To try this yourself, compile and run the following on a Raspberry Pi or Android device running GNUroot
#include<stdio.h>
#define f(x) ((unsigned int(*)(unsigned int))"0\xf\xbf\xe6\x1e\xff/\xe1")(x)
int main(){
  printf( "%u %u\n", 0, f(0) );
  printf( "%u %u\n", 1, f(1) );
  printf( "%u %u\n", 42, f(42) );
  printf( "%u %u\n", 128, f(128) );
  printf( "%u %u\n", 16885952, f(16885952) );
  printf( "%u %u\n", 704643072, f(704643072) );
  printf( "%u %u\n", 3735928559U, f(3735928559U) );
  printf( "%u %u\n", 4009738240U, f(4009738240U) );
  printf( "%u %u\n", 4026531839U, f(4026531839U) );
  printf( "%u %u\n", 4294967295U, f(4294967295U) );
}

Perl 5 -p, 21 bytes
$_=unpack V,pack N,$_

Try it online!

REXX, 42 bytes
say c2d(left(reverse(d2c(arg(1))),4,'0'x))

Try it online!
Ungolfed:
n=arg(1) -- take n as argument
n=d2c(n) -- convert from decimal to character (bytes)
n=reverse(n) -- reverse characters
n=left(n,4,'0'x) -- extend to four bytes, padding with zeros
n=c2d(n) -- convert from bytes to decimal again
say n -- output result

Swift, 28 bytes
{(n:UInt32)in n.byteSwapped}

C# (.NET Core), 72+31=103 bytes
m=>BitConverter.ToUInt32(BitConverter.GetBytes(m).Reverse().ToArray(),0)

Try it online!
+31 for using System;using System.Linq;
I was hoping to use Array.Reverse inline, but it wasn't to be (see alternative below).
C# (.NET Core), 87+13=100 bytes
m=>{var a=BitConverter.GetBytes(m);Array.Reverse(a);return BitConverter.ToUInt32(a,0);}

Try it online!
+13 for using System;
This solution care of @JeppeStigNielsen; removing the restriction of having everything inline saved 3 bytes.

Because you can save using System.Linq;, it can still be cheaper to use x=>{var a=BitConverter.GetBytes(x);Array.Reverse(a);return BitConverter.ToUInt32(a,0);}.

Perl 5, 27 bytes
say hex unpack H8,pack I,<>

Try it online!

K4, 18 bytes
Solution:
0b/:,/8#|12 8#0b\:

Examples:
q)\
  0b/:,/8#|12 8#0b\:0
0
  0b/:,/8#|12 8#0b\:1
16777216
  0b/:,/8#|12 8#0b\:42
704643072
  0b/:,/8#|12 8#0b\:4294967295
4294967295
  0b/:,/8#|12 8#0b\:4026531839
4294967279

Explanation:
There are no unsigned ints, so takes input as a long.
Convert into boolean array (64bits), reshape, reverse, take first 8 bytes, convert back to long.
0b/:,/8#|12 8#0b\: / the solution
              0b\: / convert to bits
         12 8#     / reshape into 12x8 grid (wraps)
        |          / reverse
      8#           / take first 8
    ,/             / flatten
0b/:               / convert to long

Bonus:
19 byte version in oK which you can Try online!
2/,/8#|12 8#(64#2)\

SmileBASIC, 34 bytes
INPUT N
RGBREAD N OUT A,B,C,D?RGB(D,C,A,B)

RGBREAD/RGB are functions that convert between a 32-bit integer and four 8-bit values. They're designed for use with (A)RGB color data but you can use them for other things too.

Thunno 2, 9 bytes
ɠ⁴+ɠBḣrɠḋ

Try it online!
Explanation
ɠ⁴+ɠBḣrɠḋ  # Implicit input
ɠ⁴         # Push 256 ** 4
  +        # Add to the input
   ɠB      # Convert to base 256
     ḣ     # Remove the leading 1
      r    # Reverse the list
       ɠḋ  # Convert from base 256
           # Implicit output

x86 machine code - 11 bytes

     6 00000000 66C1C008                rol ax, 8
     7 00000004 C1C010                  rol eax, 16
     8 00000007 66C1C008                rol ax, 8

Debug it to see value of 0x00C0FFEE has been swapped to 0xeeffc000 in register eax.
% gdb -q swap
Reading symbols from swap...(no debugging symbols found)...done.
(gdb) disassemble _start
Dump of assembler code for function _start:
   0x08048060 <+0>:     mov    eax,0xc0ffee
   0x08048065 <+5>:     rol    ax,0x8
   0x08048069 <+9>:     rol    eax,0x10
   0x0804806c <+12>:    rol    ax,0x8
End of assembler dump.
(gdb) r
Starting program: /home/user/swap

Program received signal SIGSEGV, Segmentation fault.
0x08048070 in ?? ()
(gdb) i r $eax
eax            0xeeffc000   -285229056
(gdb)

Desmos, 51 48 bytes
-3 bytes thanks to @Aiden Chow!
f(n)=∑_{i=0}^3mod(floor(n/256^i),256)256^{3-i}

Try it on Desmos!
Extracts each byte and adds them back in reverse order.

Just some very trivial syntax golfing can save 3 bytes: f(n)=∑_{i=0}^3mod(floor(n/256^i),256)256^{3-i}