题目链接
input
6
4 1
3 1 2 4
4 2
3 4 1 2
4 2
3 1 4 2
10 3
4 5 9 1 8 6 10 2 3 7
10 3
4 6 9 1 8 5 10 2 3 7
10 3
4 6 9 1 8 5 10 3 2 7
output
0
0
1
0
1
-1
题目大意:
每次给你一个长度为n的排列p(1-n每个数字仅出现一次)
再给你一个k,表示可以交换a[i]和a[j] (|i-j|=k)
每次输入第一行n和k,第二行一个排列p
问你能不能不先预处理,仅靠交换a[i]和a[j] (|i-j|=k)使排列p排好序,
如果需要,能不能只预处理一次(预处理:任意交换两个位置的值)
如果都不能就输出-1
如果不需要预处理输出0
如果需要预处理一次就输出1
解题思路:
因为可以交换间隔为k的数字无数次,题目要求判断预处理次数
其实就是判断每个数字在不在对应位置即可
对应位置:排好序的位置+k*a (a属于整数)
如果不在对应的位置,记录一次,最后计算需要预处理次数
#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
#define lowbit(x) ((x)&(-(x)))
#define int long long
#define rep(i,a,b) for(int i=(int)a,i##i=(int)b;i<=i##i;i++)
#define per(i,a,b) for(int i=(int)a,i##i=(int)b;i>=i##i;i--)
typedef long long ll;
typedef pair<int,int> PII;
typedef unsigned long long ULL;
const int N = 1000005;
const double PI = acos(-1);
void solve()
{
int n,k;cin>>n>>k;
//if(k==1){ cout<<"0\n";return;}
//else{
int all=0;
for(int i=1;i<=n;i++){
int num;cin>>num;
if(abs(num-i)%k!=0)all++;//判断和正确位置的距离是不是k的倍数即可
}
if(all==0)cout<<"0\n";//不需要预处理
else if(all==2)cout<<"1\n";//需要一次
else cout<<"-1\n";
//}
}
signed main()
{
std::ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int _ = 1;
cin>>_;
while(_--)
solve();
}