飞机花费



package work;

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

public class Airfare {
 static int T, N, mincost;
 static int data[][];
 static boolean used[];

 public static void main(String[] args) throws FileNotFoundException {
  /* Scanner sc=new Scanner(System.in); */
  Scanner sc = new Scanner(new File("src/airfare"));
  T = sc.nextInt();
  for (int t = 0; t < T; t++) {
   N = sc.nextInt();
   data = new int[N + 1][N + 1];
   used = new boolean[N + 1];
   for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= N; j++) {
     data[i][j] = sc.nextInt();
    }
   }
   mincost = 0xfffffff;
   used[1] = true;
   if (N == 1) {
    mincost = data[1][1];
   } else {
    dfs(1, 0);
   }
   System.out.println(mincost);
  }
 }

 private static void dfs(int step, int sum) {
  if (check()) {
   if (data[step][1] != 0 && mincost > sum + data[step][1])
    mincost = sum + data[step][1];
   return;
  }
  //
  if (sum > mincost)
   return;
  //
  for (int i = 1; i <= N; i++) {
   if (!used[i]) {
    if (data[step][i] != 0) {
     used[i] = true;
     dfs(i, sum + data[step][i]);
     used[i] = false;
    }
   }
  }

 }

 private static boolean check() {
  for (int i = 1; i <= N; i++) {
   if (used[i] == false)
    return false;
  }
  return true;
 }
}


、、input

2
5
0 14 4 10 20
14 0 7 8 7
4 5 0 7 16
11 7 9 0 2
18 7 17 4 0
5
9 9 2 9 5
6 3 5 1 5
1 8 3 3 3
6 0 9 6 8
6 6 9 4 8

、、output

30
18

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值