洛谷 1744 JAVA Dijkstra

显而易见,求最短路,也没有负权值,所以用的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;
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值