开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第16天,点击查看活动详情
Codeforces Round #836 (Div. 2)——C. Almost All Multiples
Problem - C - Codeforces
Given two integers nn and xx, a permutation†† pp of length nn is called funny if pipi is a multiple of ii for all 1≤i≤n−11≤i≤n−1, pn=1, and p1=x.
Find the lexicographically minimal‡‡ funny permutation, or report that no such permutation exists.
† A permutation of length nn is an array consisting of each of the integers from 11 to nn exactly once.
‡‡ Let aa and bb be permutations of length nn. Then aa is lexicographically smaller than bb if in the first position ii where aa and bb differ, ai<biai<bi. A permutation is lexicographically minimal if it is lexicographically smaller than all other permutations.
Input
The input consists of multiple test cases. The first line contains an integer tt (1≤t≤1041≤t≤104) — the number of test cases. The description of the test cases follows.
The only line of each test case contains two integers nn and x (2≤n≤2⋅10^5; 1<x≤n).
The sum of nn across all test cases does not exceed 2⋅10^5.
Output
For each test case, if the answer exists, output nn distinct integers p1,p2,…,pn (1≤pi≤n) — the lexicographically minimal funny permutation p. Otherwise, output −1−1.
Example
input
3
3 3
4 2
5 4
output
3 2 1
2 4 3 1
-1
问题解析
这一题是说,给你一个数n和x,让你用1到n的不同的数构建一个长度为n的数组,且数组的第i位数pi要是i的倍数,现在确定了第一位数是x,第n位是1,问其它的数怎么排,而且要求得到的数组字典序最小。
首先因为第一位确定是x了,那么我们就不能再用x,而第n位放的是1,所以我们可以用n替代x。
那么如果n不是x的倍数,显然是没有答案的,输出-1.
然后因为要使得字典序最小,我们可以把x之前的位置都设置成pi=i,x之后的pi,则看i还能不能放,不能放就找i最小的倍数放进去。
注意,对于x之后的且不是pi=i的位置,不光要保证pi是i的倍数,还要保证n是pi的倍数。
AC代码
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include <random>
#include<numeric>
#include<string>
#include<string.h>
#include<iterator>
#include<fstream>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
#include<queue>
#include<iomanip>
#include<bitset>
//#pragma GCC optimize(2)
//#pragma GCC optimize(3)
#define endl '\n'
#define int ll
#define PI acos(-1)
#define INF 0x3f3f3f3f
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll>PII;
const int N = 2e5 + 50, MOD = 1e9 + 7;
int a[N];
void solve()
{
int n, x;
cin >> n >> x;
if (n % x != 0)
{
cout << -1 << endl;
return;
}
a[1] = x;
a[n] = 1;
for (int i = 2; i < x; i++)
{
a[i] = i;
}
int idx = x;
for (int i = x+1; i < n; i++)
{
if (i % idx == 0 && n % i == 0)
{
a[idx] = i;
idx = i;
}
else a[i] = i;
}
if (idx != n)
a[idx] = n;
for (int i = 1; i <= n; i++)
cout << a[i] << " ";
cout << endl;
}
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int t = 1;
cin >> t;
while (t--)
{
solve();
}
return 0;
}