結果

問題 No.1604 Swap Sort:ONE
ユーザー merlin
提出日時 2021-07-16 21:46:49
言語 Java
(openjdk 23)
結果
AC  
実行時間 207 ms / 2,000 ms
コード長 1,145 bytes
コンパイル時間 2,477 ms
コンパイル使用メモリ 78,672 KB
実行使用メモリ 46,456 KB
最終ジャッジ日時 2024-07-06 08:48:36
合計ジャッジ時間 6,623 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 24
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.*;
import java.util.*;

class Main
{
    public static void main(String args[])throws Exception
    {
        BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb=new StringBuilder();
        int n=Integer.parseInt(bu.readLine());
        String s[]=bu.readLine().split(" ");
        int i,a[]=new int[n],c[]=new int[n];
        for(i=0;i<n;i++)
        {
            a[i]=Integer.parseInt(s[i])-1;
            c[a[i]]=i;
        }

        int ans=0;
        for(i=0;i<n;i++)
        if(a[i]!=i)
        {
            ArrayList<Integer> el=new ArrayList<>();
            int x=i;
            while(a[x]!=i)
            {
                //System.out.print(x+" ");
                el.add(x);
                x=c[a[x]-1];
            }
            el.add(x);
            //System.out.println(i+" "+el);
            for(x=el.size()-2;x>=0;x--)
            {
                int u=el.get(x),v=el.get(x+1);
                a[u]=a[u]^a[v]^(a[v]=a[u]);
                c[a[u]]=u;
                c[a[v]]=v;
                ans++;
            }
        }
        System.out.print(ans);
    }
}
0