41-牛栏-最短路径

                牛栏
问答问题反馈
  •  100%
  •  1000ms
  •  131072K
 

Farmer John 想让她的奶牛准备郡级跳跃比赛,贝茜和她的伙伴们正在练习跨栏。她们很累,所以她们想消耗最少的能量来跨栏。显然,对于一头奶牛跳过几个矮栏是很容易的,但是高栏却很难。于是,奶牛们总是关心路径上最高的栏的高度。

奶牛的训练场中有 N (1 le N le 300)N (1N300) 个站台,分别标记为 1..N1..N。所有站台之间有 M (1 le M le 25,000)M (1M25,000)条单向路径,第 ii 条路经是从站台 S_iSi 开始,到站台 E_iEi,其中最高的栏的高度为 H_i (1 le H_i le 1,000,000)Hi (1Hi1,000,000)。

无论如何跑,奶牛们都要跨栏。奶牛们有 T (1 le T le 40,000)T (1T40,000) 个训练任务要完成。第 ii 个任务包含两个数字 A_iAi 和 B_iBi (1 le A_i le N; 1 le B_i le N)(1AiN;1BiN),表示奶牛必须从站台 A_iAi 跑到站台 B_iBi,可以路过别的站台。奶牛们想找一条路径从站台 A_iAi 到站台 B_iBi,使路径上最高的栏的高度最小。你的任务就是写一个程序,计算出路径上最高的栏的高度的最小值。

输入格式

行 11:两个整数 N, M, TN,M,T。

行 2..M+12..M+1:包含三个整数 S_i , E_i , H_iSi,Ei,Hi

行 M+2..M+T+1M+2..M+T+1:包含两个整数,表示每个任务的起始站台和目标站台: A_i , B_iAi,Bi

输出格式

输出 TT 行,每行一个整数,表示每个任务路径上最高的栏的高度的最小值。如果无法到达,输出 -11。

输出时每行末尾的多余空格,不影响答案正确性

样例输入

5 6 3
1 2 12
3 2 8
1 3 5
2 5 3
3 4 4
2 4 8
3 4
1 2
5 1

样例输出

4
8
-1

一:用了地杰斯特拉,超时了
二:弗洛伊德过了
代码在一起:
import java.util.Scanner;

public class Main {
	public static int[][] map = new int[305][305];
	public static int[][] di = new int[305][305];
	public static int[] visit = new int[305];
	public static int n, m;
	public static int MAX = 0x3f3f3f3f;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin = new Scanner(System.in);
		n = cin.nextInt();
		m = cin.nextInt();
		int t = cin.nextInt();
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				map[i][j] = MAX;
				di[i][j] = MAX;
			}
		}

		for(int i = 0; i < m; i++) {
			int a, b, c;
			a = cin.nextInt();
			b = cin.nextInt();
			c = cin.nextInt();
			if(map[a][b] > c)
				map[a][b] = c;
		}
		floryd(); //调用弗洛伊德
		for(int k = 0; k < t; k++) {
			for(int i = 1; i <= n; i++) {
				visit[i] = 0;
			}
			int a, b;
			a = cin.nextInt();
			b = cin.nextInt();
			if(map[a][b] >= MAX) {
				System.out.println(-1);
			}
			else {
				System.out.println(map[a][b]);
			}
		}
		
	}
	
	public static void floryd() {
		for(int k = 1; k <= n; k++) {  //尝试每一个中转站
			for(int i = 1; i <= n; i++) {
				for(int j = 1; j <= n; j++) {
					if(map[i][j] > Math.max(map[i][k], map[k][j])) {
						map[i][j] = Math.max(map[i][k], map[k][j]);
					}
				}
			}
		}
		
	}
	
	public static int dij(int s, int e) {
		int ans = 0;
		int dist[] = new int[n+1];
		for(int i = 1; i <= n; i++) {
			dist[i] = map[s][i];
		}
		dist[s] = 0;
		for(int i = 0; i < n; i++) {
			int min = MAX;
			int p = 0;
			for(int j = 1; j <= n; j++) {
				if(visit[j] == 0 && min > dist[j]) {
					min = dist[j];
					p = j;
				}
			}
			if(p == 0) {
				break;
			}
			visit[p] = 1;
			//			ans += min;
			for(int j = 1; j <= n; j++) {
				if(visit[j] == 0 && map[p][j] < dist[j]) {
					dist[j] = map[p][j];
				}
			}
		}
		//		return ans;
		if(dist[e] >= MAX) {
			return -1;
		}
		return dist[e];
	}

}

  

 

  

 
原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/10474330.html