結果
| 問題 |
No.270 next_permutation (1)
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2016-05-06 11:53:08 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 918 ms / 2,000 ms |
| コード長 | 1,555 bytes |
| コンパイル時間 | 5,105 ms |
| コンパイル使用メモリ | 77,972 KB |
| 実行使用メモリ | 64,400 KB |
| 最終ジャッジ日時 | 2024-12-21 07:31:56 |
| 合計ジャッジ時間 | 11,652 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| other | AC * 15 |
ソースコード
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));}
}