prim 最小生成树算法 java实现

http://ac.jobdu.com/problem.php?pid=1024 
 
import java.util.Arrays;
import java.util.Scanner;


public class 畅通工程 {
	
	static int n,m,a,b;
	static  final long MAX = 10000000;
	static long map[][] = new long[101][101];
	static long c;
	static long ans;
	static boolean visited[] = new boolean[101];
	
	static long lowcost[] = new long[101];
	static int close[] = new int[101];
	public static void main(String[] args) {
		
		Scanner s = new Scanner(System.in);
		while(s.hasNext()){
			n = s.nextInt();
			m = s.nextInt();
			//System.out.prlongln(n + "   " + m);
			if(n == 0)
				break;
			
			
			for(int i=0; i<m; i++)
				for(int j=0; j<m; j++)
					map[i][j] = MAX;
			Arrays.fill(close, 0, m, 0);
			Arrays.fill(visited, 0, m, false);
			for(long i=0; i<n; i++){
				a = s.nextInt() -1;
				b = s.nextInt() -1;
				c = s.nextLong();
				if(c < map[a][b]){
					map[a][b] = c;
					map[b][a] = c;
				}
					
			}
			if(n < m-1)
			{
				System.out.println("?");
				continue;
			}
			sovle();
			boolean flag = true;
			for(int i=0; i<m; i++){
				if(!visited[i]){
					flag = false;
					break;
				}
			}
		
			if(flag && ans < MAX)
				System.out.println(ans);
			else
				System.out.println("?");


		}
		
		
		
	}
	
	static boolean sovle(){
		ans = 0;
		visited[0] = true;
		
		for(int i=0; i<m; i++)
			lowcost[i] = map[0][i];
		
		for(int i=1; i<m; i++){
			int index = 0;
			long min = MAX;
			for(int j=1; j<m; j++){
				if(!visited[j] && map[0][j] < min){
					min = map[0][j];
					index = j;
				}
			}
			if(min >= MAX)
				return false;
			ans += map[0][index];
			visited[index] = true;
			map[0][index] = 0;			
			long temp = 0;
			for(int j=0; j<m; j++){
				if(!visited[j] && map[index][j] < MAX){
					temp = map[0][index] + map[index][j];
					if(temp < map[0][j]){
//						indexs[j] = index;
						map[0][j] = temp;
					}
					
				}
			}
		}
		return true;
	}


}


你可能感兴趣的:(java,算法,String,Class,import)