`
qingtangpaomian
  • 浏览: 37640 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

USACO - 3.1.1 - Agri-Net

阅读更多

 

原创文章转载请注明出处

摘要:Prim算法 , 图论

一. 题目翻译

1. 描述:
农民约翰被选为他们镇的镇长!他其中一个竞选承诺就是在镇上建立起互联网,并连接到所有的农场。当然,他需要你的帮助。 约翰已经给他的农场安排了一条高速的网络线路,他想把这条线路共享给其他农场。为了使花费最少,他想铺设最短的光纤去连接所有的农场。 你将得到一份各农场之间连接费用的列表,你必须找出能连接所有农场并所用光纤最短的方案。 每两个农场间的距离不会超过100000

2. 格式:

          INPUT FORMAT:

          第一行: 农场的个数,N(3<=N<=100)。
          第二行..结尾: 后来的行包含了一个N*N的矩阵,表示每个农场之间的距离。理论上,他们是N行,每行由N个用空格分隔的数组成,实际上,他们限制在80个字符,因此,某些行会紧接着另一些行。当然,对角线将会是0,因为不会有线路从第i个农场到它本身。

          OUTPUT FORMAT:

          只有一个输出,其中包含连接到每个农场的光纤的最小长度。

3. SAMPLE:
          SAMPLE INPUT:
4
0  4  9 21
4  0  8 17
9  8  0 16
21 17 16  0
          SAMPLE OUTPUT:
28

          
二.  题解

1. 题意理解(将问题分析清楚,大致用什么思路):
          基本的Prim算法,按照算法实现的步骤来做就可以了。首先将起始点加入最小生成树中,然后遍历每次取最小的边加入,重复n-1次,就可以得到一颗完整的最小生成树。

 

2. 启示:
          Prim算法是基本的图论算法,注意积累。

三.  代码
/*
ID:fightin1
LANG:JAVA
TASK:agrinet
*/
package session_3_1_1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class agrinet {

	public static void main(String[] args) throws Exception {
//		Scanner in = new Scanner(System.in);
//		PrintWriter pw = new PrintWriter(System.out);
		
		Scanner in = new Scanner(new BufferedReader(new FileReader(
		"agrinet.in")));
		PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(
		"agrinet.out")));
		
		ArrayList<Integer> now = new ArrayList<Integer>();//在最小生成树当中的节点
		ArrayList<Integer> next = new ArrayList<Integer>();//不在最小生成树中的节点
		
		int num = in.nextInt();
		int[][] dist = new int[num][num];

		for (int i=0;i<num;i++){
			next.add(i);
			for (int j=0;j<num;j++){
				dist[i][j] = in.nextInt();
				dist[j][i] = dist[i][j];
			}
		}
		
		now.add(0);
		next.remove(new Integer(0));
		
		int cnt = 0;
		for(int i=1;i<num;i++){
			int min = Integer.MAX_VALUE;
			int nextNode = -1;
			for (int j=0;j<now.size();j++){
				for (int k=0;k<next.size();k++){
					if (dist[now.get(j)][next.get(k)]!=0){ 
						if(dist[now.get(j)][next.get(k)]<min){
							min = dist[now.get(j)][next.get(k)];
							nextNode = next.get(k);
						}
					}
				}
			}
			cnt = cnt + min;
			now.add(nextNode);
			next.remove(new Integer(nextNode));
		}
//		for (int i=0;i<num;i++){
//			for(int j=0;j<num;j++){
//				for(int k=0;k<num;k++){
//					if (dist[j][i]+dist[i][k]<dist[j][k]){
//						dist[j][k] = dist[j][i] + dist[i][k];
//					}
//				}
//			}
//		}
//		
//		int max = 0;
//		for (int i=0;i<num;i++){
//			for (int j=0;j<num;j++){
//					if (dist[i][j]>max){
//						max = dist[i][j];
//					}
//			}
//		}
		pw.println(cnt);
		pw.close();
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics