zoukankan      html  css  js  c++  java
  • PAT (Advanced Level) 1067. Sort with Swap(0,*) (25)

    只对没有归位的数进行交换。

    分两种情况:

    如果0在最前面,那么随便拿一个没有归位的数和0交换位置。

    如果0不在最前面,那么必然可以归位一个数字,将那个数字归位。

    这样模拟一下即可。

    #include<cstdio>
    #include<cstring>
    #include<cmath>
    #include<vector>
    #include<map>
    #include<stack>
    #include<queue>
    #include<string>
    #include<algorithm>
    using namespace std;
    
    int n;
    int a[100000+10];
    queue<int>Q;
    int pos[100000+10];
    
    int main()
    {
        scanf("%d",&n);
        for(int i=0;i<n;i++) scanf("%d",&a[i]);
        for(int i=0;i<n;i++) pos[a[i]]=i;
        for(int i=0;i<n;i++)
        {
            if(a[i]==0) continue;
            if(a[i]!=i) Q.push(a[i]);
        }
    
        int ans=0;
        while(1)
        {
            if(a[0]==0)
            {
                while(!Q.empty())
                {
                    int head=Q.front(); Q.pop();
                    if(a[head]==head) continue;
                    else
                    {
                        ans++;
                        int pos1=pos[0];
                        int pos2=pos[head];
                        swap(a[pos1],a[pos2]);
                        swap(pos[head],pos[0]);
                        break;
                    }
                }
                if(Q.empty()) break;
            }
            else
            {
                ans++;
                int pos1=pos[0];
                int pos2=pos[pos[0]];
                int num1=0;
                int num2=pos[0];
                swap(a[pos1],a[pos2]);
                swap(pos[num1],pos[num2]);
            }
        }
        printf("%d
    ",ans);
        return 0;
    }
  • 相关阅读:
    软链接
    yum
    vm
    tengine
    创智LIUNX
    作业11
    作业10
    作业9
    作业8
    作业7
  • 原文地址:https://www.cnblogs.com/zufezzt/p/5632353.html
Copyright © 2011-2022 走看看