Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define MAX 100000
- #define mod 1000000007
- long long store[MAX + 5];
- void fill_store (void) {
- long long i; store[0] = 1;
- for (i = 1; i <= MAX; i++) store[i] = (i * (store[i - 1] % mod)) % mod;
- }
- int parity (long long perm[], int len) {
- int check[len + 5], j; int cycle = 1;
- memset(check, 0, sizeof check); int res = 0;
- for (j = 1; j <= len; j++) {
- if (check[j] == 0) {
- check[j] = 1; cycle++; int k = j;
- while (check[perm[k]] == 0) {
- check[perm[k]] = 1;
- k = perm[k];
- cycle++;
- }
- res += (cycle % 2);
- cycle = 1;
- }
- }
- return res % 2;
- }
- // incomplete
- long long index (long long perm[], int len) {
- long long res = 0;
- for (int j = 1; j <= len; j++)
- res += (((perm[j] - 1) * store[len - j]) % mod);
- return res % mod;
- }
- bool is_circ (long long A[], long long B[], int len) {
- long long AA[len + len + 5], k, one;
- for (k = 1; k <= len; k++) {
- AA[k] = A[k]; AA[len + k] = A[k];
- if (A[k] == 1) one = k;
- }
- bool res = true;
- for (k = one; k < one + len; k++) {
- if (AA[k] != B[k]) {
- res = false;
- break;
- }
- }
- return res;
- }
- int main() {
- fill_store();
- int i, T, N, K; long long P[MAX + 5], Q[MAX + 5];
- scanf("%d", &T); while (T--) {
- scanf("%d %d", &N, &K); bool flag = true;
- for (i = 1; i <= N; i++) scanf("%lld", P + i);
- for (i = 1; i <= N; i++) {
- scanf("%lld", Q + i);
- if (flag && Q[i] != P[i]) flag = false;
- }
- int parP = parity(P, N), parQ = parity(Q, N);
- long long lex = index(Q, N);
- if (K == 1) printf("%lld\n", flag ? lex : -1);
- else if (K == N) printf("%lld\n", is_circ(P, Q, N) ? Q[1] : -1);
- else if (K % 2) printf("%lld\n", parP == parQ ? lex/2 : -1);
- else printf("%lld\n", lex);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement