隧道 之后自己写的

package xj;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Tunnels {
 static int T, N, H, V;
 static int S[][];
 static int c1, r1, m1, c2, r2, m2;
 static int used[];
 static int mincost;
 static int minrow[];

 public static void main(String[] args) throws FileNotFoundException {
  /* Scanner sc=new Scanner(System.in); */
  Scanner sc = new Scanner(new File(“src/1”));
  T = sc.nextInt();
  for (int t = 0; t < T; t++) {
   N = sc.nextInt();
   H = sc.nextInt();
   V = sc.nextInt();
   S = new int[V][H];
   minrow = new int[V];
   for (int i = 0; i < V; i++) {
    for (int j = 0; j < H; j++) {
     S[i][j] = sc.nextInt();
    }
   }
   c1 = sc.nextInt();
   r1 = sc.nextInt();
   m1 = sc.nextInt();
   c2 = sc.nextInt();
   r2 = sc.nextInt();
   m2 = sc.nextInt();
   mincost = 0xfffffff;
   for (int i = 0; i < V; i++) {
    minrow[i] = find(i);
   }
   for (int i = 0; i <= V – 1 – (N – 1) * 2; i++) {
    dfs(1, i, minrow[i]);
   }
   System.out.println(mincost);
  }

 }

 private static void dfs(int step, int last, int sum) {
  if(step==N){
   if(mincost>sum){mincost=sum;}return;
  }
  for (int next = last+2; next < V-1-(N-1-step)*2; next++) {
   sum+=minrow[next]+(m1*m1+m2*m2)*(next-last);
   dfs(step+1,next,sum);
  }
 }

 private static int find(int p) {
  int rowsum=0xfffffff;
  for (int i = 0; i <= H; i++) {
   int sum = 0;//一开始错了,注意,这里sum必须写在for循环里,因为每次要初始化
             for (int j = 0; j < i; j++) {
    sum+=S[p][j]*c1;//一开始没注意p,写成了i,此处注意;
   }
             for (int j = i; j < H; j++) {
     sum+=S[p][j]*c2;
    }
             if(H-i>i){
              sum+=(H-i-i-1)*r2;
             }
             if(H-i<i){
              sum+=(i-(H-i)-1)*r1;
             }
             if(rowsum>sum){rowsum=sum;}
  }
  //
  return rowsum;
 }

}

、、input

3
 1 3 1
 42 3 99
 4 19 3
 4 1 5
 1 5 1
 1 4 1 3 11
 7 2 3
 2 6 4
 3 5 6
 50 50 50 50 50
 50 50 50 50 50
 50 50 50 50 50
 50 50 50 50 50
 50 50 50 50 50
 50 50 50 50 50
 10 10 10
 20 10 5

。。output

576
57
170
8120
1940000

点赞