Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

贴Java代码。 O(V*E) ,带注释

Posted by haqishen at 2015-01-08 21:27:33 on Problem 3259 and last updated at 2015-01-08 21:40:42
//下一页也有一人贴了java的代码,那个代码结构非常清晰但是略感冗余
//我在这里同样用BellmanFord算法实现,但代码精简了很多,java排行榜22(当时)
//最差的情况计算量是V*E (点总数 乘以 边总数)

import java.io.*;
import java.util.*;
public class Main{

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

//              这个链表用于保存所有的边,包括虫洞
		LinkedList<edge> es;
//              记录各点距离,自动初始化全为0
		int dist[];

		int F = new Integer(br.readLine());
		while(F-->0){
			String input[] = br.readLine().split("\\s");
			int N = new Integer(input[0]), M = new Integer(input[1]), W = new Integer(input[2]); 
			dist = new int[N+1];
			es = new LinkedList<edge>();
			
//                      在这里输入所有的边,i<M时输入的是双向的小径
//                      i>=M时输入的是虫洞,单向,距离变为负数
			for(int i = 0; i < M+W; i++){
				String input2[] = br.readLine().split("\\s");
				int a = new Integer(input2[0]);
				int b = new Integer(input2[1]);
				int d = new Integer(input2[2]);
				if(i<M){
					es.add(new edge(a,b,d));
					es.add(new edge(b,a,d));
				}else{
					es.add(new edge(a,b,-d));
				}
			}
			
//                      下面是BellmanFord主算法,原理网上多得是我就不说了。
			for(int i = 1; i <= N; i++){
				boolean ud = false;
				
				for(edge e : es){
					int d = dist[e.from] + e.dist;
					if(d < dist[e.to]){
						dist[e.to] = d;
						ud = true;
					}
				}

				if(!ud){
					System.out.println("NO");
					break;
				}
				if(i==N){
					System.out.println("YES");
					break;
				}
			}	
		}
	}
}

class edge{
	int from, to, dist;
	edge(int from, int to,int dist){
		this.from = from;
		this.to = to;
		this.dist = dist;
	}
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator