UVa10917 - Walk Through the Forest(单源最短路径及动态规划)

Jimmy experiences a lot of stress at work these days, especially sincehis accident made working difficult. To relax after a hard day, helikes to walk home. To make things even nicer, his office is on oneside of a forest, and his house is on the other. A nice walk throughthe forest, seeing the birds and chipmunks is quite enjoyable.

The forest is beautiful, and Jimmy wants to take a different routeeveryday. He also wants to get home before dark, so he always takes apath to make progress towards his house. He considers taking apath fromA toB to be progress if there existsa route from B to his home that is shorter thanany possible route fromA.Calculate how many different routes through the forest Jimmy might take.

Input

Input contains several test cases followed by a line containing 0.Jimmy has numbered each intersection or joining of paths starting with 1.His office is numbered 1, and his house is numbered 2. Thefirst line of each test case gives the number of intersections N,1 < N ≤ 1000, and the number of paths M.The following M lines each containa pair of intersections a b and an integerdistance 1 ≤ d ≤ 1000000 indicating a path of length dbetween intersection a and a different intersection b.Jimmy may walk a path any direction he chooses.There is at most one path between any pair of intersections.

Output

For each test case, output a single integer indicating the number of different routesthrough the forest. You may assume that this number does notexceed 2147483647.

Sample Input

5 6
1 3 2
1 4 2
3 4 3
1 5 12
4 2 34
5 2 24
7 8
1 3 1
1 4 1
3 7 1
7 4 1
7 5 1
6 7 1
5 2 1
6 2 1
0

Output for Sample Input

2
4
用邻接表建图,Dijkstra求出从home到其它点的最短距离,动态规划求出从office到home的可行的路径的个数

10917 -Walk Through the Forest AcceptedJava0.9520.00061015 mins ago

import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.PriorityQueue;
import java.util.Arrays;

public class Main implements Runnable{
	private static final boolean DEBUG = false;
	private Scanner cin;
	private PrintWriter cout;
	private int n, m;
	private Vertex[] vertexs;
	private int[] d;
	private boolean[] vis;
	private int[] memo;
	
	class Vertex
	{
		Edge firstEdge;
	}
	
	class Edge
	{
		int from, to, w;
		Edge next;
	}
	
	class Node implements Comparable<Node>
	{
		int u, w;
		
		public int compareTo(Node other)
		{
			return w - other.w;
		}
	}
	
	private void init() 
	{
		try {
			if (DEBUG) {
				cin = new Scanner(new BufferedInputStream(new FileInputStream("d:\\OJ\\uva_in.txt")));
			} else {
				cin = new Scanner(new BufferedInputStream(System.in));
			}

			
			cout = new PrintWriter(new OutputStreamWriter(System.out));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean input() 
	{
		n = cin.nextInt();
		if (n == 0) return false;
		
		vertexs = new Vertex[n + 1];
		for (int i = 1; i <= n; i++) {
			vertexs[i] = new Vertex();
			vertexs[i].firstEdge = null;
		}
		m = cin.nextInt();
		
		
		int a, b, d;
		for (int i = 0; i < m; i++) {
			a = cin.nextInt();
			b = cin.nextInt();
			d = cin.nextInt();
			Edge edge = new Edge();
			edge.from = a; edge.to = b; edge.w = d; edge.next = vertexs[a].firstEdge;
			vertexs[a].firstEdge = edge;
			
			edge = new Edge();
			edge.from = b; edge.to = a; edge.w = d; edge.next = vertexs[b].firstEdge;
			vertexs[b].firstEdge = edge;
		}
		return true;
	}
	
	private void Dijkstra(int source)
	{
		d = new int[n + 1];
		vis = new boolean[n + 1];
		
		for (int i = 1; i <= n; i++) d[i] = Integer.MAX_VALUE;
		d[source] = 0;
		
		PriorityQueue<Node> pq = new PriorityQueue<Node>();
		Node node = new Node();
		node.u = source; node.w = d[source];
		pq.add(node);
		
		while (!pq.isEmpty()) {
			node = pq.poll();
			int u = node.u;
			if (vis[u]) continue;
			
			vis[u] = true;
			for (Edge edge = vertexs[u].firstEdge; edge != null; edge = edge.next) {
				int v = edge.to, w = edge.w;
				if (d[u] + w < d[v]) {
					d[v] = d[u] + w;
					node = new Node();
					node.u = v;
					node.w = d[v];
					pq.add(node);
				}
			}
		}
	}
	
	private int dp(int x)
	{
		if (memo[x] != -1) return memo[x];
		
		int ans = 0;
		for (Edge edge = vertexs[x].firstEdge; edge != null; edge = edge.next) {
			int v = edge.to;
			if (d[x] > d[v]) ans += dp(v);
		}
		
		return memo[x] = ans;
	}
	
	private void solve() 
	{
		Dijkstra(2);
		
		memo = new int[n + 1];
		Arrays.fill(memo, -1);
		memo[2] = 1;
		
		int ans = dp(1);
		cout.println(ans);
		cout.flush();
	}

	public void run()
	{
		init();
		
		while (input()){
			solve();
		}
	}
	
	public static void main(String[] args) 
	{
		new Thread(new Main()).start();
	}
}


第二种方法 ,用SPFA求单源最短路径

10917 - Walk Through the Forest AcceptedJava0.9660.00061514 mins ago

import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.PrintWriter;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Arrays;

public class Main implements Runnable{
	private static final boolean DEBUG = false;
	private Scanner cin;
	private PrintWriter cout;
	private int n, m;
	private Vertex[] vertexs;
	private int[] d;
	private boolean[] inq;
	private int[] memo;
	
	class Vertex
	{
		Edge firstEdge;
	}
	
	class Edge
	{
		int from, to, w;
		Edge next;
	}
	
	private void init() 
	{
		try {
			if (DEBUG) {
				cin = new Scanner(new BufferedInputStream(new FileInputStream("d:\\OJ\\uva_in.txt")));
			} else {
				cin = new Scanner(new BufferedInputStream(System.in));
			}

			
			cout = new PrintWriter(new OutputStreamWriter(System.out));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private boolean input() 
	{
		n = cin.nextInt();
		if (n == 0) return false;
		
		vertexs = new Vertex[n + 1];
		for (int i = 1; i <= n; i++) {
			vertexs[i] = new Vertex();
			vertexs[i].firstEdge = null;
		}
		m = cin.nextInt();
		
		
		int a, b, d;
		for (int i = 0; i < m; i++) {
			a = cin.nextInt();
			b = cin.nextInt();
			d = cin.nextInt();
			Edge edge = new Edge();
			edge.from = a; edge.to = b; edge.w = d; edge.next = vertexs[a].firstEdge;
			vertexs[a].firstEdge = edge;
			
			edge = new Edge();
			edge.from = b; edge.to = a; edge.w = d; edge.next = vertexs[b].firstEdge;
			vertexs[b].firstEdge = edge;
		}
		return true;
	}
	
	private void SPFA(int source)
	{
		d = new int[n + 1];
		inq = new boolean[n + 1];
		
		for (int i = 1; i <= n; i++) d[i] = Integer.MAX_VALUE;
		d[source] = 0;
		inq[source] = true;
		
		Queue<Integer> queue = new LinkedList<Integer>();
		queue.add(source);
		
		while (!queue.isEmpty()) {
			int u = queue.poll();
			inq[u] = false;
			
			for (Edge edge = vertexs[u].firstEdge; edge != null; edge = edge.next) {
				int v = edge.to, w = edge.w;
				if (d[u] + w < d[v]) {
					d[v] = d[u] + w;
					if (!inq[v]) {
						inq[v] = true;
						queue.add(v);
					}
				}
			}
		}
	}
	
	private int dp(int x)
	{
		if (memo[x] != -1) return memo[x];
		
		int ans = 0;
		for (Edge edge = vertexs[x].firstEdge; edge != null; edge = edge.next) {
			int v = edge.to;
			if (d[x] > d[v]) ans += dp(v);
		}
		
		return memo[x] = ans;
	}
	
	private void solve() 
	{
		SPFA(2);
		
		memo = new int[n + 1];
		Arrays.fill(memo, -1);
		memo[2] = 1;
		
		int ans = dp(1);
		cout.println(ans);
		cout.flush();
	}

	public void run()
	{
		init();
		
		while (input()){
			solve();
		}
	}
	
	public static void main(String[] args) 
	{
		new Thread(new Main()).start();
	}
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
单源最短路径问题是图论中的一个经典问题,其中Dijkstra算法是一种常用的解决方法。下面是一个演示如何使用动态规划来更新单源最短路径的过程: 1. 首先,我们需要定义一个带权有向图G,其中包含顶点和边。每个边都有一个权值,表示从一个顶点到另一个顶点的距离或代价。 2. 接下来,我们选择一个起始顶点作为源点,并将其距离设置为0,其他顶点的距离设置为无穷大。 3. 然后,我们开始迭代更新顶点的距离。对于每个顶点v,我们检查从源点到v的距离是否可以通过经过其他顶点来缩短。如果可以,我们更新v的距离为更短的值。 4. 在更新过程中,我们还需要记录每个顶点的前驱顶点,以便在最后构建最短路径时使用。 5. 最后,当所有顶点的距离都被更新后,我们可以根据记录的前驱顶点信息构建最短路径。 下面是一个示例代码,演示了如何使用动态规划来更新单源最短路径: ```python import sys def dijkstra(graph, start): # 初始化距离和前驱顶点 distance = {vertex: sys.maxsize for vertex in graph} distance[start] = 0 previous = {vertex: None for vertex in graph} # 更新距离和前驱顶点 for _ in range(len(graph)): for vertex in graph: for neighbor, weight in graph[vertex].items(): if distance[vertex] + weight < distance[neighbor]: distance[neighbor] = distance[vertex] + weight previous[neighbor] = vertex return distance, previous # 示例图 graph = { 'A': {'B': 5, 'C': 3}, 'B': {'D': 2}, 'C': {'B': 1, 'D': 6}, 'D': {'A': 1} } start_vertex = 'A' distances, previous_vertices = dijkstra(graph, start_vertex) # 打印最短路径 for vertex in distances: path = [] current_vertex = vertex while current_vertex is not None: path.insert(0, current_vertex) current_vertex = previous_vertices[current_vertex] print(f"Shortest path to {vertex}: {' -> '.join(path)}") ``` 这段代码演示了如何使用Dijkstra算法来更新单源最短路径。它首先初始化距离和前驱顶点,然后通过迭代更新距离和前驱顶点的方式找到最短路径。最后,它打印出每个顶点的最短路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kgduu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值