Official

C - Inverse Prefix Sum Editorial by en_translator


We can find the elements \(A_i\) from the beginning, one by one.

Solution 1

  • \(A_1=S_1\).
  • \(S_2=A_1+A_2\), so \(A_2=S_2-A_1\).
  • \(S_3=A_1+A_2+A_3\), so \(A_3=S_3-A_1-A_2\).
  • \(\vdots\)

Thus, \(A_k=S_k-A_1-\ldots-A_{k-1}\), and when we try to find \(A_k\), we already have \(A_1,\ldots,A_{k-1}\), so we can use these equations to find \(A_k\).

Sample code (C)

#include<stdio.h>

int main(){
	int n;
	scanf("%d",&n);
	int s[10];
	for(int i=0;i<n;i++)scanf("%d",s+i);

	int a[10];
	for(int i=0;i<n;i++){
		// Find a[i]
		int temp=s[i];
		for(int j=0;j<i;j++)temp-=a[j];
		a[i]=temp;
	}

	for(int i=0;i<n;i++)printf("%d%c",a[i],i==n-1?'\n':' ');
}

Solution 2

Since \(S_i=(A_1+\ldots+A_{i-1})+A_i=S_{i-1}+A_i\), it hold that \(S_i-S_{i-1}=A_i\). We can use this equation to find \(A_i\). By defining \(S_0=0\), this holds for \(i=1\) too. Be careful not to cause an out-of-bounds access for the index \((i-1)\).

Sample code (C)

#include<stdio.h>

int main(){
	int n;
	scanf("%d",&n);
	int s[11];
	s[0]=0;
	for(int i=1;i<=n;i++)scanf("%d",s+i);

	int a[10];
	for(int i=0;i<n;i++)a[i]=s[i+1]-s[i];
	
	for(int i=0;i<n;i++)printf("%d%c",a[i],i==n-1?'\n':' ');
}

Bonus

Since the complexity for Solution 1 is \(O(N^2)\), if \(N=200000\), the execution time will be long. On the other hand, the complexity for Solution 2 is \(O(N)\), so you can find the answer for \(N=200000\) fast enough. When you try problem C and later, consider the differences in complexities too.

posted:
last update: