欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > Trick : 排列映射技巧

Trick : 排列映射技巧

2024/10/24 4:43:03 来源:https://blog.csdn.net/2301_78527293/article/details/143165935  浏览:    关键词:Trick : 排列映射技巧

Trick : 排列映射技巧

假设给你排列 a a a 以及排列 b b b ,现在需要把 a a a 变成 b b b

假设存在数组 c i c_i ci ,令 c b i = i c_{b_i}=i cbi=i ,令 a i = c a i a_i=c_{a_i} ai=cai ,即可完成映射,使得 b b b 变为 1 , 2 , ⋯ , n 1,2,\cdots,n 1,2,,n ,相当于变成排序问题。

void mapping(){for(int i = 1; i <= n; i ++){cin >> a[i];}for(int i = 1; i <= n; i ++){cin >> x;b[x] = i;}for(int i = 1; i <= n; i ++){a[i] = b[a[i]];}
}

例题

oph is playing a card game. She has n n n cards and each card has a unique number of 1 , 2 ⋯ n 1,2\cdots n 1,2n. In this game, Toph can operate the deck of the cards. We may wish to assume that the cards from the top to the bottom of the deck are p 1 , p 2 , ⋯ p n p_1,p_2,\cdots p_n p1,p2,pn (a permutation), then each operation must be one of the following two cases:

  1. Place the top card at the bottom of the deck, that is, change the order of the deck into p 2 , p 3 ⋯ p n , p 1 p_2,p_3\cdots p_n,p_1 p2,p3pn,p1.
  2. Place the second card from the top at the bottom of the deck, that is, change the order of the deck into p 1 , p 3 ⋯ p n , p 2 p_1,p_3\cdots p_n,p_2 p1,p3pn,p2
    Now, you know that the initial order(from top to bottom) of Toph’s deck is a 1 , a 2 , ⋯ a n a_1,a_2,\cdots a_n a1,a2,an, and Toph wants to change the order of the deck into b 1 , b 2 , ⋯ b n b_1,b_2,\cdots b_n b1,b2,bn after some operations. Please construct the operation sequence to help Toph implement the change.
    Toph has no patience. So the number of operations should not exceed n 2 n^2 n2.

b b b 映射,相当于对 a a a 排序了。

发现执行 n n n 1 1 1 a a a 数组不变。

在其中第 i i i 执行一次 2 2 2 ,最后输出的 a a a 相当于 a i a_i ai a i + 1 a_{i+1} ai+1 交换了位置。

利用冒泡排序的思想,如果 b j < b j + 1 b_j<b_{j+1} bj<bj+1 ,输出 1 1 1 ; 否则输出 2 2 2

这样最后一个位置一定最大。

每一轮输出 n n n 个数字即可,可以选择出一个第 i i i 大元素,共 n − 1 n-1 n1 轮。

#include<bits/stdc++.h>
using namespace std;
#define int long longint const N = 1100;int n, x, a[N], b[N];void solve(){cin >> n;for(int i = 1; i <= n; i ++){cin >> a[i];}for(int i = 1; i <= n; i ++){cin >> x;b[x] = i;}for(int i = 1; i <= n; i ++){a[i] = b[a[i]];}for(int i = 1; i < n; i ++){for(int j = 1; j < n; j ++){if(a[j] > a[j + 1]){swap(a[j], a[j + 1]);cout << '2';}else cout << '1';}cout << '1';}cout << '\n';
}signed main(){ios::sync_with_stdio(false);cin.tie(0), cout.tie(0);int T = 1;cin >> T;while (T --){solve();}return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com