D - Coming of Age Celebration
Source: atcoder
Difficulty: 400

Problem Statement
On a certain planet, there are
N
aliens, all of whom are minors.
The
i
-th alien currently has
A_i
stones, and will become an adult exactly
i
years later.
When someone becomes an adult on this planet, every
adult
who has at least one stone gives exactly one stone as a congratulatory gift to the alien who has just become an adult.
Find how many stones each alien will have after
N
years.
Assume that no new aliens will be born in the future.
Constraints
1 \leq N \leq 5 \times 10^5
0 \leq A_i \leq 5 \times 10^5
All input values are integers.
Input
The input is given from Standard Input in the following format:
N
A_1
A_2
\ldots
A_N
Output
Let
B_i
be the number of stones owned by the
i
-th alien after
N
years. Print
B_1, B_2, \ldots, B_N
in this order, separated by spaces.
Sample Input 1
4
5 0 9 3
Sample Output 1
2 0 10 5
Let
C_i
be the number of stones that the
i
-th alien has at a given time.
Initially,
(C_1, C_2, C_3, C_4) = (5, 0, 9, 3)
.
After
1
year,
(C_1, C_2, C_3, C_4) = (5, 0, 9, 3)
.
After
2
years,
(C_1, C_2, C_3, C_4) = (4, 1, 9, 3)
.
After
3
years,
(C_1, C_2, C_3, C_4) = (3, 0, 11, 3)
.
After
4
years,
(C_1, C_2, C_3, C_4) = (2, 0, 10, 5)
.
Sample Input 2
5
4 6 7 2 5
Sample Output 2
0 4 7 4 9
Sample Input 3
10
2 9 1 2 0 4 6 7 1 5
Sample Output 3
0 2 0 0 0 4 7 10 4 10

C++ solution:
#include<bits/stdc++.h>
using namespace::std;

const int N = 500000 + 5;

int n;
int a[N];
int ac[N];

int main() {
    cin.tie(0) -> sync_with_stdio(false);
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> a[i];
    for(int i = 1; i <= n; i++) {
        ac[i] += ac[i - 1];
        a[i] += ac[i];
        int l = i + 1;
        int r = min(i + a[i], n);
        ac[l] += 1;
        ac[r + 1] -= 1;
        a[i] -= r - l + 1;
        cout << a[i] << " \n"[i == n];
    }
    return 0;
}

Go solution:
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"sort"
	"strconv"
	"strings"
)

var sc = bufio.NewScanner(os.Stdin)
var wr = bufio.NewWriter(os.Stdout)

func main() {
	defer wr.Flush()
	sc.Split(bufio.ScanWords)
	sc.Buffer([]byte{}, math.MaxInt32)

	N := readInt()
	A := readInts(N)

	s := 0
	r := make([]int, N)
	// 配れる石の数：min(A[i],N-i-1)
	for i := 0; i < N; i++ {
		A[i] += s
		num := min(A[i], N-i-1)
		A[i] -= num
		s++
		r[i+num]++
		s -= r[i]
	}
	outInts(A)

}

func out(x ...interface{}) {
	fmt.Fprintln(wr, x...)
}

func outStrings(x []string) {
	out(strings.Join(x, " "))
}

func outInts(x []int) {
	y := make([]string, len(x))
	for i := 0; i < len(x); i++ {
		y[i] = strconv.Itoa(x[i])
	}
	outStrings(y)
}

func readInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func readFloat() float64 {
	sc.Scan()
	i, e := strconv.ParseFloat(sc.Text(), 64)
	if e != nil {
		panic(e)
	}
	return i
}

func readInts(N int) []int {
	ret := make([]int, N)
	for i := 0; i < N; i++ {
		ret[i] = readInt()
	}
	return ret
}

func readText() string {
	sc.Scan()
	return sc.Text()
}

// min, max, aSub, absなど基本関数
func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// min for n entry
func nMin(a ...int) int {
	ret := a[0]
	for _, e := range a {
		ret = min(ret, e)
	}
	return ret
}

// max for n entry
func nMax(a ...int) int {
	ret := a[0]
	for _, e := range a {
		ret = max(ret, e)
	}
	return ret
}

func chMin(a *int, b int) bool {
	if *a < b {
		return false
	}
	*a = b
	return true
}

func chMax(a *int, b int) bool {
	if *a > b {
		return false
	}
	*a = b
	return true
}

func aSub(a, b int) int {
	if a > b {
		return a - b
	}
	return b - a
}

func abs(a int) int {
	if a >= 0 {
		return a
	}
	return -a
}

func lowerBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] >= x
	})
	return idx
}

func upperBound(a []int, x int) int {
	idx := sort.Search(len(a), func(i int) bool {
		return a[i] > x
	})
	return idx
}

Java solution:
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.function.IntPredicate;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;
import java.util.stream.Collectors;

public class Main {
    static In in = new FastIn();
    static Out out = new Out(false);
    static final long inf = 0x1fffffffffffffffL;
    static final int iinf = 0x3fffffff;
    static final double eps = 1e-9;
    static long mod = 998244353;
    void solve() {
        int n = in.nextInt();
        int[] a = in.nextIntArray(n);
        int[] b = new int[n+1];
        int[] ans = new int[n];
        for (int i = 0; i < n; i++) {
            if(i!=0)b[i] += b[i-1];
            a[i] += b[i];
            ans[i] = Math.max(0,a[i]-(n-i-1));
            b[i]++;
            b[Math.min(n,i+a[i]+1)]--;
        }
        out.println(ans);
    }

    public static void main(String... args) {
        new Main().solve();
        out.flush();
    }
}

class FastIn extends In {
    private final BufferedInputStream reader = new BufferedInputStream(System.in);
    private final byte[] buffer = new byte[0x10000];
    private int i = 0;
    private int length = 0;

    public int read() {
        if (i == length) {
            i = 0;
            try {
                length = reader.read(buffer);
            } catch (IOException ignored) {
            }
            if (length == -1) {
                return 0;
            }
        }
        if (length <= i) {
            throw new RuntimeException();
        }
        return buffer[i++];
    }

    String next() {
        StringBuilder builder = new StringBuilder();
        int b = read();
        while (b < '!' || '~' < b) {
            b = read();
        }
        while ('!' <= b && b <= '~') {
            builder.appendCodePoint(b);
            b = read();
        }
        return builder.toString();
    }

    String nextLine() {
        StringBuilder builder = new StringBuilder();
        int b = read();
        while (b != 0 && b != '\r' && b != '\n') {
            builder.appendCodePoint(b);
            b = read();
        }
        if (b == '\r') {
            read();
        }
        return builder.toString();
    }

    int nextInt() {
        long val = nextLong();
        if ((int)val != val) {
            throw new NumberFormatException();
        }
        return (int)val;
    }

    long nextLong() {
        int b = read();
        while (b < '!' || '~' < b) {
            b = read();
        }
        boolean neg = false;
        if (b == '-') {
            neg = true;
            b = read();
        }
        long n = 0;
        int c = 0;
        while ('0' <= b && b <= '9') {
            n = n * 10 + b - '0';
            b = read();
            c++;
        }
        if (c == 0 || c >= 2 && n == 0) {
            throw new NumberFormatException();
        }
        return neg ? -n : n;
    }
}

class In {
    private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in), 0x10000);
    private StringTokenizer tokenizer;

    String next() {
        try {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                tokenizer = new StringTokenizer(reader.readLine());
            }
        } catch (IOException ignored) {
        }
        return tokenizer.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }

    char[] nextCharArray() {
        return next().toCharArray();
    }

    String[] nextStringArray(int n) {
        String[] s = new String[n];
        for (int i = 0; i < n; i++) {
            s[i] = next();
        }
        return s;
    }

    char[][] nextCharGrid(int n, int m) {
        char[][] a = new char[n][m];
        for (int i = 0; i < n; i++) {
            a[i] = next().toCharArray();
        }
        return a;
    }

    int[] nextIntArray(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = nextInt();
        }
        return a;
    }

    int[] nextIntArray(int n, IntUnaryOperator op) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = op.applyAsInt(nextInt());
        }
        return a;
    }

    int[][] nextIntMatrix(int h, int w) {
        int[][] a = new int[h][w];
        for (int i = 0; i < h; i++) {
            a[i] = nextIntArray(w);
        }
        return a;
    }

    long[] nextLongArray(int n) {
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            a[i] = nextLong();
        }
        return a;
    }

    long[] nextLongArray(int n, LongUnaryOperator op) {
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            a[i] = op.applyAsLong(nextLong());
        }
        return a;
    }

    long[][] nextLongMatrix(int h, int w) {
        long[][] a = new long[h][w];
        for (int i = 0; i < h; i++) {
            a[i] = nextLongArray(w);
        }
        return a;
    }

    List<List<Integer>> nextEdges(int n, int m, boolean directed) {
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            res.add(new ArrayList<>());
        }
        for (int i = 0; i < m; i++) {
            int u = nextInt() - 1;
            int v = nextInt() - 1;
            res.get(u).add(v);
            if (!directed) {
                res.get(v).add(u);
            }
        }
        return res;
    }
}

class Out {
    private final PrintWriter out = new PrintWriter(System.out);
    private final PrintWriter err = new PrintWriter(System.err);
    boolean autoFlush = false;
    boolean enableDebug;

    Out(boolean enableDebug) {
        this.enableDebug = enableDebug;
    }

    void println(Object... args) {
        if (args == null || args.getClass() != Object[].class) {
            args = new Object[] {args};
        }
        out.println(Arrays.stream(args).map(obj -> {
            Class<?> clazz = obj == null ? null : obj.getClass();
            return clazz == Double.class ? String.format("%.10f", obj) :
                    clazz == byte[].class ? Arrays.toString((byte[])obj) :
                            clazz == short[].class ? Arrays.toString((short[])obj) :
                                    clazz == int[].class ? Arrays.toString((int[])obj) :
                                            clazz == long[].class ? Arrays.toString((long[])obj) :
                                                    clazz == char[].class ? Arrays.toString((char[])obj) :
                                                            clazz == float[].class ? Arrays.toString((float[])obj) :
                                                                    clazz == double[].class ? Arrays.toString((double[])obj) :
                                                                            clazz == boolean[].class ? Arrays.toString((boolean[])obj) :
                                                                                    obj instanceof Object[] ? Arrays.deepToString((Object[])obj) :
                                                                                            String.valueOf(obj);
        }).collect(Collectors.joining(" ")));
        if (autoFlush) {
            out.flush();
        }
    }

    void debug(Object... args) {
        if (!enableDebug) {
            return;
        }
        if (args == null || args.getClass() != Object[].class) {
            args = new Object[] {args};
        }
        err.println(Arrays.stream(args).map(obj -> {
            Class<?> clazz = obj == null ? null : obj.getClass();
            return clazz == Double.class ? String.format("%.10f", obj) :
                    clazz == byte[].class ? Arrays.toString((byte[])obj) :
                            clazz == short[].class ? Arrays.toString((short[])obj) :
                                    clazz == int[].class ? Arrays.toString((int[])obj) :
                                            clazz == long[].class ? Arrays.toString((long[])obj) :
                                                    clazz == char[].class ? Arrays.toString((char[])obj) :
                                                            clazz == float[].class ? Arrays.toString((float[])obj) :
                                                                    clazz == double[].class ? Arrays.toString((double[])obj) :
                                                                            clazz == boolean[].class ? Arrays.toString((boolean[])obj) :
                                                                                    obj instanceof Object[] ? Arrays.deepToString((Object[])obj) :
                                                                                            String.valueOf(obj);
        }).collect(Collectors.joining(" ")));
        err.flush();
    }

    void println(int a) {
        out.println(a);
        if (autoFlush) {
            out.flush();
        }
    }

    void println(long a) {
        out.println(a);
        if (autoFlush) {
            out.flush();
        }
    }

    void println(double a) {
        out.println(String.format("%.10f", a));
        if (autoFlush) {
            out.flush();
        }
    }

    void println(String s) {
        out.println(s);
        if (autoFlush) {
            out.flush();
        }
    }

    void println(char[] s) {
        out.println(String.valueOf(s));
        if (autoFlush) {
            out.flush();
        }
    }

    void println(int[] a) {
        StringJoiner joiner = new StringJoiner(" ");
        for (int i : a) {
            joiner.add(Integer.toString(i));
        }
        out.println(joiner);
        if (autoFlush) {
            out.flush();
        }
    }

    void println(long[] a) {
        StringJoiner joiner = new StringJoiner(" ");
        for (long i : a) {
            joiner.add(Long.toString(i));
        }
        out.println(joiner);
        if (autoFlush) {
            out.flush();
        }
    }

    void flush() {
        err.flush();
        out.flush();
    }
}

JavaScript solution:
const main = function(input) {
    const [N] = input[0].split(" ").map(Number);
    const A = input[1].split(" ").map(Number);
    const df = [];
    for (var i = 0; i < A.length - 1; i++) {
        df[i] = A[i + 1] - A[i];
    }
    const ans = [];
    let l = A[0];
    for (var i = 0; i < A.length; i++) {
        if (l > N - i - 1) {
            ans.push(l - N + i + 1);
            df[i]++;
        } else {
            ans.push(0);
            df[i]++;
            df[i + l]--;
        }
        l += df[i];
    }
    console.log(ans.join(" "));
};

(async () => {
    const buffers = [];
    for await (const chunk of process.stdin) buffers.push(chunk);
    const buffer = Buffer.concat(buffers);
    const text = buffer.toString();
    main(text.split("\n"))
})()

Python solution:
n=int(input())
a=[int(x) for x in input().split()]
minus=[0 for i in range(n)]
ans=[-1 for _ in range(n)]
for i in range(n):
    ans[i]=a[i]-(n-1-i)+i
for i in range(n):
    minus[i]=minus[i-1]+minus[i]
    ans[i]-=minus[i]
    if ans[i]<0:
        minus[ans[i]]+=1
        ans[i]=0
print(*ans)

Ruby solution:
N,*A = $<.read.split.map{_1.to_i}
s,S = 0,[0]*N
puts A.map.with_index{|a,i|
	s += S[i]
	a += s
	if i+a+1<N
		S[i+a+1] -= 1
		a = 0
	else
		a -= N-i-1
	end
	s += 1
	next a
}*' '