結果

問題 No.270 next_permutation (1)
ユーザー 37zigen37zigen
提出日時 2016-05-06 11:53:08
言語 Java19
(openjdk 21)
結果
AC  
実行時間 726 ms / 2,000 ms
コード長 1,555 bytes
コンパイル時間 2,480 ms
コンパイル使用メモリ 74,140 KB
実行使用メモリ 65,188 KB
最終ジャッジ日時 2023-08-23 07:01:34
合計ジャッジ時間 9,867 ms
ジャッジサーバーID
(参考情報)
judge13 / judge11
このコードへのチャレンジ(β)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 124 ms
55,952 KB
testcase_01 AC 156 ms
56,008 KB
testcase_02 AC 149 ms
56,440 KB
testcase_03 AC 123 ms
55,608 KB
testcase_04 AC 166 ms
54,524 KB
testcase_05 AC 154 ms
56,136 KB
testcase_06 AC 149 ms
55,872 KB
testcase_07 AC 148 ms
55,428 KB
testcase_08 AC 213 ms
58,912 KB
testcase_09 AC 333 ms
60,320 KB
testcase_10 AC 707 ms
62,772 KB
testcase_11 AC 713 ms
64,544 KB
testcase_12 AC 726 ms
65,188 KB
testcase_13 AC 659 ms
64,656 KB
testcase_14 AC 670 ms
64,912 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

package yukicoder;
import java.util.Arrays;
import java.util.Scanner;
public class Main{
	public static void main(String[] args)throws Exception{
		new Main().solve();
	}
	void solve(){
		Scanner sc=new Scanner(System.in);
		int N=sc.nextInt();
		int K=sc.nextInt();
		int[] P=new int[N];
		int[] B=new int[N];
		for(int i=0;i<N;i++)P[i]=sc.nextInt();
		for(int i=0;i<N;i++)B[i]=sc.nextInt();
		long s=0;
		for(int i=0;i<N;i++){
			s+=Math.abs(P[i]-B[i]);
		}
		long ret=0;

		for(int t=0;t<K;t++){
			ret+=s;
			int i;
			for(i=N-2;i>=0&&P[i]>P[i+1];i--)
				;
			if(i==-1){
				s=0;
				for(int u=0;u<N;u++){
					P[u]=u+1;
					s+=Math.abs(P[u]-B[u]);
				}
				continue;
			}
			int j;
			for(j=i+1;j<N&&P[i]<P[j];j++)
				;
			s-=Math.abs(P[i]-B[i]);
			s-=Math.abs(P[j-1]-B[j-1]);
			int d=P[i];
			P[i]=P[j-1];
			P[j-1]=d;
			s+=Math.abs(P[i]-B[i]);
			s+=Math.abs(P[j-1]-B[j-1]);
			
			for(int p=i+1,q=N-1;p<q;p++,q--){
				s-=Math.abs(P[p]-B[p]);
				s-=Math.abs(P[q]-B[q]);
				d=P[p];
				P[p]=P[q];
				P[q]=d;
				s+=Math.abs(P[p]-B[p]);
				s+=Math.abs(P[q]-B[q]);
			}
		}
		System.out.println(ret);
	}
	boolean nextPermutation(int[] a){
		int n=a.length;
		int i;
		for(i=n-2;i>=0&&a[i]>a[i+1];i--)
			;
		if(i==-1)return false;//5,4,3,2,1 のような形になっている。
		int j;
		for(j=i+1;j<n&&a[i]<a[j];j++)
			;
		int d=a[i];
		a[i]=a[j-1];
		a[j-1]=d;
		for(int p=i+1,q=n-1;p<q;p++,q--){
			d=a[p];
			a[p]=a[q];
			a[q]=d;
		}
		tr(a);
		return true;
	}
	void tr(Object...o){System.out.println(Arrays.deepToString(o));}
}
0