显而易见,求最短路,也没有负权值,所以用的Djikstra。就是写着太折磨了。。。。
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main
{
static xy place[];
static int n, m, cnt;
static int head[];
static node edge[];
static PriorityQueue<map> que;
static int start, end;
static boolean vis[];
static double dist[];
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
n = sc.nextInt();
place = new xy[n + 10];
for (int i = 1; i <= n; i++) {
place[i] = new xy(sc.nextInt(), sc.nextInt());
}
// --------------------------------------数据输入准备部分
m = sc.nextInt();
dist = new double[1005];
Arrays.fill(dist, Integer.MAX_VALUE);//求最小!!!用maxvalue
head = new int[20005];
edge = new node[20005];
vis = new boolean[20005];
que = new PriorityQueue<>();
for (int i = 0; i < edge.length; i++) {
edge[i] = new node();
}
for (int i = 0; i < m; i++) {
int x, y;
x = sc.nextInt();
y = sc.nextInt();
double value = nn(place[x].x, place[x].y, place[y].x, place[y].y);
add(x, y, value);
add(y, x, value);
}
// -----------------------------数据输入准备部分
// System.out.println(Arrays.toString(dist));测试
start = sc.nextInt();
end = sc.nextInt();
dist[start]=0;//!!!!!!!!!!!!!!!!!!!!!!!起始位置为0!
dijistra();
System.out.printf("%.2f",dist[end]);
}
}
static void dijistra()
{
que.add(new map(0, start));
while (!que.isEmpty()) {
int u = que.poll().y;
if (vis[u])
continue;
vis[u] = true;
for (int i = head[u]; i != 0; i = edge[i].next) {
int v = edge[i].to;
double value = edge[i].value;
if (dist[v] >= dist[u] + value) {
dist[v] = dist[u] + value;
que.add(new map(dist[v], v));
}
}
}
}
static class map implements Comparable<map>//按照x顺序排放
{
double x;
int y;
@Override
public int compareTo(Main.map o)
{
// TODO Auto-generated method stub
return (int) (x-o.x);
}
public map(double dist, int y)
{
this.x = dist;
this.y = y;
}
}
static double nn(int x1, int y1, int x2, int y2)
{
double l1 = Math.pow(x2 - x1, 2);
double l2 = Math.pow(y2 - y1, 2);
return Math.sqrt(l1 + l2);
}
static void add(int u, int v, double value)
{
edge[++cnt].to = v;
edge[cnt].value = value;
edge[cnt].next = head[u];
head[u] = cnt;
}
static class node
{
int to, next;
double value;
}
static class xy
{
int x, y;
public xy(int x, int y)
{
this.x = x;
this.y = y;
}
}
}