Skip to content
GitHub Twitter

Codeforces #713(Div.3) E: Permutation by Sum [EN]

Problem Overview

  • Consider the permutation 1 to n called P.
  • The parameters l,r,s that satisfies 1lrn and 1sn(n+1)2 are given.
  • Find the permutation which satisfies Pl+Pl+1+...+Pr=s.
  • Print any permutation of length n that fits the condition above if such a permutation exists; otherwise, -1.

Problem Explanation

First, consider the minimum and the maximum value we can generate with the length rl+1.
Hereafter, we define k=rl+1.

Minimum Value
As an arithmetic sequence with first term 1, term number m, and tolerance 1, we can derive the minimum value.
min(m)=m(m+1)2

Maximum Value
As an arithmetic sequence with first term x, term number m, and tolerance -1, we can derive the maximum value.

max(x,m)=m(2x+(m1)1)2
max(x,m)=m(2xm+1)2

Any number s that satisfies min(k)smax(n,k) meet the condition.

Coding
First, we prepare the vector res with size n to push the results.
Consider in descending order.
Start the for loop from n,
if i meets the condition max(i,k)s0 and simin(k1), put i to the res[l+k] and replace k=k1,s=si.
Iterate this until k becomes 0, and then if s=0 is achieved, we find the permuation; otherwise, prints -1.
The remaining part of the implementation is to insert the unused numbers into the empty parts of the vector.

Source Code