编程语言:Java
题目:
题解:背模板(虽然我是照着打的),AC的背后藏着StreamTokenizer读取数据,不然等着TL吧!
结果:AC
Floyd 算法:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static Scanner sc = new Scanner(new BufferedInputStream(System.in));
static int[][] graph = new int[102][102];
static int res= (int) 1e8, num, n, m;
public static void main(String[] args) throws IOException {
in.nextToken();
n = (int) in.nval;
in.nextToken();
m = (int) in.nval;
for(int i=0;i<102;i++)
Arrays.fill(graph[i], (int) 1e8);
for(int i=0;i<102;i++)
graph[i][i]=0;
for (int i = 0; i < m; i++) {
in.nextToken();int s = (int) in.nval;
in.nextToken();int e = (int) in.nval;
in.nextToken();int val= (int) in.nval;
graph[s][e] = val;
graph[e][s] = val;
}
for(int k=1;k<=n;k++){
for (int i = 1; i <=n; i++) {
for (int i1 = 1; i1 <= n; i1++) {
graph[i][i1]=Math.min(graph[i][i1],graph[i][k]+graph[k][i1]);
}
}
}
for(int i=1;i<=n;i++){
int ans=0;
for(int j=1;j<=n;j++){
ans=Math.max(ans,graph[i][j]);
}
if(ans<res){
res=ans;
num=i;
}
}
if(res==1e8)
out.println(0);
else
out.println(num+" "+res);
out.flush();
}
}=
Dijkstra 算法:
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static Scanner sc = new Scanner(new BufferedInputStream(System.in));
static int[][] graph = new int[102][102];
static int[] d = new int[102];
static boolean[] f = new boolean[102];
static int res = (int) 1e8, num, n, m;
public static void main(String[] args) throws IOException {
in.nextToken();
n = (int) in.nval;
in.nextToken();
m = (int) in.nval;
for (int i = 0; i < m; i++) {
in.nextToken();
int s = (int) in.nval;
in.nextToken();
int e = (int) in.nval;
in.nextToken();
int val = (int) in.nval;
graph[s][e] = val;
graph[e][s] = val;
}
for (int s = 1; s <= n; s++) {
dijkstra(s);
int ans = 0;
for (int i = 1; i <= n; i++) {
if (i != s && d[i] > ans)
ans = d[i];
}
if (res > ans) {
res = ans;
num = s;
}
}
if (res != 1e8)
out.println(num + " " + res);
else
out.println(0);
out.flush();
}
private static void dijkstra(int s) {
Arrays.fill(d, (int) 1e8);
Arrays.fill(f, false);
d[s] = 0;
while (true) {
int v = -1;
for (int u = 1; u <= n; u++) {
if (!f[u] && (v == -1 || d[u] < d[v]))
v = u;
}
if (v == -1) break;
f[v] = true;
for (int u = 1; u <= n; u++) {
if (graph[v][u] != 0)
d[u] = Math.min(d[u], d[v] + graph[v][u]);
}
}
}
}