题目链接:https://ac.nowcoder.com/acm/contest/5671/E
题目大意:
给出n,k,问有没有一个1-n的排列,使得子串长度从1~n,总存在子串的和模n等于k。
解题思路:
1-n的和是(n+1)n/2能模n余k,则打表可知,奇数的时候k必须为0(别忘了为0的时候不输出k,因为是1—n的排列!),而偶数的时候k是n/2
肯定是把n放在最前面,k放在第二个,后面就是1,n-1,2,n-2...
如果n是奇数,P={n,k,1,n-1,2,n-2...}
如果n是偶数,P={n,k,1,n-1,2,n-2...}
*代码:**
#include<bits/stdc++.h> using namespace std; int main() { int n, k; scanf("%d%d",&n,&k); int s = (1+n)*n/2; if(s % n != k) { cout << -1 << endl; return 0; } if(n & 1) { if(k != 0) { cout << -1 << endl; } else { cout << n <<" "; for(int i = 1; i <= n/2; i++) { cout << n-i << " " << i << " "; } cout << "\n"; } } else { if(k != n/2) { cout << -1 << endl; } else { cout << n << " " << k << " "; for(int i = 1; i < n/2; i++) { cout << n-i << " " << i << " "; } cout << "\n"; } } }