• PAT Sort with Swap(0, i)


    1067 Sort with Swap(0, i)

    Given any permutation of the numbers {0, 1, 2,..., N−1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:

    1. Swap(0, 1) => {4, 1, 2, 0, 3}
    2. Swap(0, 3) => {4, 1, 2, 3, 0}
    3. Swap(0, 4) => {0, 1, 2, 3, 4}

    Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.

    Input Specification:

    Each input file contains one test case, which gives a positive N (≤105) followed by a permutation sequence of {0, 1, ..., N−1}. All the numbers in a line are separated by a space.

    Output Specification:

    For each case, simply print in a line the minimum number of swaps need to sort the given permutation.

    Sample Input:

    1. 10
    2. 3 5 7 2 6 4 9 0 8 1

    Sample Output:

    9

    总结:自己是真滴蠢,怎么就是想不到怎么做呢???

    自己代码:

     题目中所给的例子是可以顺利执行的,但是 遇到 1 0 3 5 7 2 4 9 8这样顺序的,就出错了,早早的就结束了排序

    1. #include
    2. using namespace std;
    3. const int N=100010;
    4. int a[N],b[N];//a用来存储题目给出的数据的顺序,b存储a[i]在a数组中的位置
    5. int n;
    6. int main(){
    7. int cot=0;
    8. scanf("%d",&n);
    9. for(int i=0;i
    10. scanf("%d",&a[i]);
    11. b[a[i]]=i;
    12. }
    13. if(b[0]!=1){//如果0所在的位置不是1的话,需要把0交换到位置1
    14. int temp=a[1];
    15. swap(a[1],a[b[0]]);
    16. swap(b[0],b[temp]);
    17. cot++;
    18. }
    19. while(a[0]!=0){
    20. swap(a[b[b[0]]],a[b[0]]);
    21. b[0]=b[b[0]];
    22. cot++;
    23. }
    24. for(int i=0;iprintf("%d ",a[i]);
    25. puts("");
    26. printf("%d\n",cot);
    27. return 0;
    28. }

    还是多学习学习大佬的代码! 

    1. #include
    2. using namespace std;
    3. int main() {
    4. int n, t, cnt = 0, a[100010];
    5. cin >> n;
    6. for(int i = 0; i < n; i++){
    7. cin >> t;
    8. a[t] = i;
    9. }
    10. for(int i = 1; i < n; i++) {
    11. //这样的结构还可以顺便检验序列是否是递增
    12. if(i != a[i]) {
    13. while(a[0] != 0) {
    14. swap(a[0],a[a[0]]);
    15. cnt++;
    16. }
    17. if(i != a[i]) {//反例:3 0 2 1 4 //第一次循环后,a[0]==0 a[1]==1
    18. //需要继续往下循环,看看下面的数字是否是按序排列的
    19. swap(a[0],a[i]);
    20. cnt++;
    21. }
    22. }
    23. }
    24. cout << cnt;
    25. return 0;
    26. }

    好好学习,天天向上!

    我要考研

  • 相关阅读:
    FME针对尖锐角及小缝隙处理
    java学习第181天,javaWeb学习第40天,复习第17天;泛型、p228-236(08/03)-6.5h
    【立创机械狗从0到成品PCB画图总结】
    解密Prompt系列3. 冻结LM微调Prompt: Prefix-Tuning & Prompt-Tuning & P-Tuning
    【Linux】信号简介与触发信号的几种方式
    数学建模文写作----个人笔记
    el-table超过宽度强制显示滚动条
    看完抱你学会Exchanger
    Makefile入门(二)
    Android-CAS与原子变量(无锁并发和有锁并发)
  • 原文地址:https://blog.csdn.net/weixin_50679551/article/details/127135203