USACO 2.4 Bessie Come Home (Floyd最短路径)

本文展示了一个使用C语言实现的图算法示例,通过定义牧场间的距离矩阵并利用Floyd-Warshall算法来找出任意两点间最短路径。代码中详细介绍了如何读取输入文件、解析牧场间的连接及距离,并更新距离矩阵以反映最短路径。

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

#include <stdio.h>
#define DEBUG 1
#define TESTCASES 9
#define INF 1e8

int distanceMatrix[52][52];

int char2Int(char cha){
	if (cha >= 'A' && cha <= 'Z')
		return cha - 'A';
	else
		return cha - 'a' + 26;;
}

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "input7.txt";
		//inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif

	int from, to;
	for (from = 0; from < 52; from++)
		for (to = from; to < 52; to++)
			if (from == to)
				distanceMatrix[from][to] = 0;
			else
				distanceMatrix[from][to] = distanceMatrix[to][from] = INF;

	int numOfPaths;
	scanf("%d", &numOfPaths);
	char cha;
	int path;
	for (path = 1; path <= numOfPaths; path++){
		char onePasture, anotherPasture;
		int distance;
		scanf("%c", &cha);
		scanf("%c %c %d", &onePasture, &anotherPasture, &distance);
		from = char2Int(onePasture);
		to = char2Int(anotherPasture);
		if (distance < distanceMatrix[from][to])
			//相同的两个牧场之间可能有多条路,选最短的
			distanceMatrix[from][to] = distanceMatrix[to][from] = distance;	
	}

	int pass;
	for (pass = 0; pass < 52; pass++)
		for (from = 0; from < 52; from++)
			for (to = from + 1; to < 52; to++)
				if (distanceMatrix[from][pass] + distanceMatrix[pass][to] < distanceMatrix[from][to])
					distanceMatrix[from][to] = distanceMatrix[to][from] = distanceMatrix[from][pass] + distanceMatrix[pass][to];

	char result;
	int minDistance = INF;
	to = 25;
	for (from = 0; from < 25; from++)
		if (distanceMatrix[to][from] < minDistance){
			result = from;
			minDistance = distanceMatrix[to][from];
		}

	printf("%c %d\n", 'A' + result, minDistance);

#if DEBUG
	}
#endif
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值