結果

問題 No.270 next_permutation (1)
ユーザー 37zigen37zigen
提出日時 2016-05-06 11:52:14
言語 Java21
(openjdk 21)
結果
WA  
実行時間 -
コード長 1,554 bytes
コンパイル時間 2,672 ms
コンパイル使用メモリ 77,972 KB
実行使用メモリ 59,200 KB
最終ジャッジ日時 2024-04-15 13:30:25
合計ジャッジ時間 10,844 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 160 ms
41,316 KB
testcase_01 AC 193 ms
41,184 KB
testcase_02 AC 183 ms
41,452 KB
testcase_03 AC 148 ms
41,316 KB
testcase_04 AC 197 ms
41,528 KB
testcase_05 AC 194 ms
41,512 KB
testcase_06 AC 178 ms
41,572 KB
testcase_07 WA -
testcase_08 WA -
testcase_09 WA -
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
権限があれば一括ダウンロードができます

ソースコード

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();
		int 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