最小旅行线路-动规
程序员文章站
2022-03-24 20:49:03
...
Sample Input
3
1 1 2 2 3 3
Sample Output
9
import java.util.ArrayList;
import java.util.Scanner;
public class Main{
static int dp[][]=new int[200005][2];
static int map1[][]=new int[200005][2];
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
for (int i = 1; i <=2*n ; i++) {
int x=scanner.nextInt();
if (map1[x][0]==0)map1[x][0]=i;
else map1[x][1]=i;
}
dp[1][1]=map1[1][1]-1;
dp[1][0]=map1[1][0]-1;
for (int i = 2; i <=n ; i++) {
if (dp[i-1][1]+Math.abs(map1[i][0]-map1[i-1][1])+dp[i-1][0]+
Math.abs(map1[i][1]- map1[i-1][0])<dp[i-1][1]+
Math.abs(map1[i][1]-map1[i-1][1])+dp[i-1][0]+Math.abs(map1[i][0]- map1[i-1][0])){
dp[i][0]=dp[i-1][1]+Math.abs(map1[i][0]-map1[i-1][1]);
dp[i][1]=dp[i-1][0]+Math.abs(map1[i][1]-map1[i-1][0]);
}else {
dp[i][1]=dp[i-1][1]+Math.abs(map1[i][1]-map1[i-1][1]);
dp[i][0]=dp[i-1][0]+Math.abs(map1[i][0]-map1[i-1][0]);
}
}
System.out.println(dp[n][1]+dp[n][0]);
}
}