牛客多校(2020第六场)E Easy Construction
示例1
输入
2 1
输出
1 2
说明
The sum of subintervals [1],[1,2][1],[1,2][1],[1,2] both satisfy ≡1(mod2), and their lengths are 1,21,21,2 respectively.
示例2
输入
3 1
输出
-1
题解:
- 如果有解,那么 n(n+1)/2 % n == k,因为长度为n的子区间是P本身,P的元素之和为n(n+1)/2.
- 假设k满足上述条件,此时一定有解。如果是奇数,则k=0,则P={n, 1, n-1, 2, n-2, ..},若为偶数,则P={n, n/2, 1, n-1, 2, n-2, ...}
1 #include<iostream> 2 using namespace std; 3 4 int n, k; 5 6 void solve() { 7 cin >> n >> k; 8 int sum = n * (n+1) / 2; 9 if (sum % n != k) cout << "-1\n"; 10 else { 11 if (n % 2 == 0) { 12 cout << n << " " << n / 2; 13 for (int i = 1; i <= n/2 -1; i++) { 14 cout << " " << i << " " << n - i; 15 } 16 } 17 else { 18 cout << n; 19 for (int i = 1; i <= n/2; i++) { 20 cout << " " << i << " " << n - i; 21 } 22 } 23 } 24 } 25 26 int main() { 27 solve(); 28 cout << "\n"; 29 return 0; 30 }