单源最短路(Bellman - Ford算法)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/c_yejiajun/article/details/88073367

题目描述(POJ2139)

牛们最近在拍电影,所以他们准备去玩一个游戏——“六度分割”的变体。 游戏是这样进行的:每个牛离自己的距离是0度,如果两个不同的牛同时出现在一个电影里,那么他们之间的距离为1度,如果两只牛从未一起工作,但它们都与第三只牛一起工作,那么他们之间的距离为2度。 这N(2<=N<=300)头牛对找出那只牛与所有牛之间的平均距离最短感兴趣。当然,不算上他自己。这些牛拍了M(1<=M<=10000)部电影,并且保证每两个牛之间都有一定的关系。求那一头牛与其它牛距离的平均值最小值,把它乘100输出。

可以这么理解,如果A和B是一个集合里的,AB之间的距离为1
如果B和C是一个集合里的,AC之间的距离为2
自己与自己的距离为1

代码实现

定义一个类,n1到n2的距离为cast

class E{
	int n1, n2, cast;
}

储存数据,将所有的集合储存起来

		Scanner sc = new Scanner(System.in);
		
		int n = sc.nextInt();
		int m = sc.nextInt();
		E [] e = new E[100000];
		int index = 0;
		
		for(int i = 0; i < m; i++){
			
			int num = sc.nextInt();
			int [] team = new int [num];
			
			for(int j = 0; j < num; j++){
				team[j] = sc.nextInt();
			}
			
			for(int j = 0; j < num - 1; j++){
				for(int k = j + 1; k < num; k++){
					E ee = new E();
					ee.n1 = team[j];
					ee.n2 = team[k];
					ee.cast = 1;
					
					e[index++] = ee;
					
			}

处理每一条边

		int result = Integer.MAX_VALUE;
		
		for(int i = 1; i <= n; i++){
			int [] d = new int [n + 1];
			
			for(int j = 1; j <= n; j++){
				d[j] = Integer.MAX_VALUE;
			}
			
			d[i] = 0;
			
			while(true){
				
				boolean update = false;
				
				for(int j = 0; j < e.length; j++){
					if(e[j] == null) break;
					
					if(d[e[j].n1] != Integer.MAX_VALUE){
						if(d[e[j].n2] > d[e[j].n1] + e[j].cast){
							d[e[j].n2] = d[e[j].n1] + e[j].cast;
							update = true;
						}
					}
					
					if(d[e[j].n2] != Integer.MAX_VALUE){
						if(d[e[j].n1] > d[e[j].n2] + e[j].cast){
							d[e[j].n1] = d[e[j].n2] + e[j].cast;
							update = true;
						}
					}
					
				}
				
				if(!update) break;
			}
			
			for(int j = 1; j <= n; j++){
				d[0] += d[j];
			}
			
			if(d[0] * 100 < result && d[0] != 0){
				result = d[0] * 100;
			}
		}
		
		System.out.println(result / (n - 1));

猜你喜欢

转载自blog.csdn.net/c_yejiajun/article/details/88073367
今日推荐