Розбір
The number can range from to . Given a fixed value of , the remaining numbers in the sequence are uniquely determined. Iterate from to , restore the sequence and verify whether it constitutes a permutation of numbers from to (all must be distinct and fall within the range from to ). Once the reconstructed sequence forms a permutation, print it and terminate the program.
Since , then or .
Example
Let . Then sequence generates the following sequence :
The sequence is a permutation. The following relationship holds: and .
If, for example, we choose , then the following sequence will be restored from the input sequence :
The sequence is not a permutation.
Algorithm realization
Declare the arrays. The array will be used to verify whether is a permutation.
#define MAX 1001 int a[MAX], b[MAX], used[MAX];
Read the input data.
scanf("%d", &n); for (i = 0; i < n - 1; i++) scanf("%d", &b[i]);
Iterate over the value of from to .
for (a0 = 1; a0 <= n; a0++) { a[0] = a0;
Compute the elements of the sequence using the formula .
for (i = 1; i < n; i++) a[i] = b[i - 1] - a[i - 1];
Initialize the array with zeroes.
for (i = 1; i <= n; i++) used[i] = 0;
Check if is a permutation. Each value of must appear in the sequence only once and be within the range from to . The variable will be set to if the sequence is not a permutation.
flag = 0; for (i = 0; i < n; i++) { if (a[i] < 1 || a[i] > n || used[a[i]]) { flag = 1; break; } used[a[i]] = 1; }
If the sequence is a permutation, print it and terminate the program.
if (flag == 0) { for (i = 0; i < n; i++) printf("%d ", a[i]); printf("\n"); return 0; } }
Python realization
Read the input data.
n = int(input()) b = list(map(int, input().split()))
Declare the lists. The list will be used to check if is a permutation.
a = [0] * n used = [0] * (n + 1)
Iterate over the value of from to .
for a0 in range(1, n + 1): a[0] = a0
Compute the elements of the sequence using the formula .
for i in range(1, n): a[i] = b[i - 1] - a[i - 1]
Initialize the list with zeroes.
for i in range(1, n + 1): used[i] = 0
Check if is a permutation. Each value of must appear in the sequence only once and be within the range from to . The variable will be set to if the sequence is not a permutation.
flag = 0 for i in range(n): if a[i] < 1 or a[i] > n or used[a[i]]: flag = 1 break used[a[i]] = 1
If the sequence is a permutation, print it and terminate the program.
if flag == 0: print(*a) break