Convenient Location AOJ0189

本文介绍使用Floyd算法解决寻找最佳宿舍位置的问题。通过计算任意两点间最短路径,遍历每个点并计算路径总和,选取最小值对应的点作为最佳位置。涉及Floyd算法、最短路径计算及数据读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意直接有道翻译

思路:Floyd算法计算出任意两点之间最短路径,遍历每一个点,计算路径和,取最小值

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <queue>
#include <cmath>
#include <fstream>
const int MAX = 1e4+10;
const int INF = 1e6;

using namespace std;

int n;
int cs;
int d[MAX][MAX] = {0};//两点间最短距离 
int sum, ans;
int pos;//最合适位置 

//弗洛伊德最短路径 
void  Floyd(){
	for(int i=0; i<=cs; i++)
		for(int j=0; j<=cs; j++)
			for(int k =0; k<=cs; k++){
				d[j][k] = min(d[j][k], d[j][i]+d[i][k]);
			}			
}
 
//测试函数 
int main(){
	ifstream cin ("D:\\钢铁程序员\\程序数据\\062最佳宿舍.txt");//从文件读取数据流,省去手动输入的麻烦 
	if(!cin){//读取如果失败 
		cout << "ERROR" << endl;
	}
	while(cin >> n, n){
		cs = 0;//最大城市编号 
		//i->i 距离为零,其他初始化为INF(因为数据不止一个) 
		for(int i=0; i<=n; i++)
			for(int j=0; j<=n; j++){
				if(i == j)
					d[i][j] = 0;
				else
					d[i][j] = INF;
			}
		for(int i=0; i<n; i++){
			int a, b, c;
			cin >> a >> b >> c;
			d[a][b] = c;
			d[b][a] = c;
			cs = max(cs, a);
			cs = max(cs, b);
		}
				
		Floyd();		
		//找最合适位置 
		ans = INF;
		for(int i=0; i<=cs; i++){
			sum = 0;
			for(int j=0; j<=cs; j++){
				sum += d[i][j];
			}
			if(sum < ans){
				pos = i;
				ans = sum;
			}
		} 
		cout << pos << " " << ans << endl;
	}
	cin.close();//打开文件以后要关闭 
	return 0;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值