Sicilly 1031. Campus (Floyd 算法)

用惯了Dijkstra,尝试着用老师上课教的Floyd算法。


Floyd算法是一个经典的动态规划算法,改算法利用了中间节点的概念,简单地说就是求一点 i 到 一点 j 的的距离,可以通过其中中间点进而进行求解。

详情可以参考一下博客:

http://www.cppblog.com/wing/archive/2011/03/10/141511.html


#include <iostream>
#include <stack>
#include <cstdio>
#include <queue>
#include <vector>
#include <map>
#include <algorithm>
#include <iomanip>
#include <cstring>

using namespace std;
const int maxn = 1000000;

map<string, int> places;

int tot = 0;

void floyd(int n,int dis[][200]) {
	for (int k = 0; k < n; k++)
		for (int i = 0; i < n; i++)
			if (dis[i][k] < maxn)
				for (int j = 0; j < n; j++)
					if (dis[k][j] < maxn)
						dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]);
}

int main() {
	int tst;
	cin >> tst;
	int dis[200][200];
	while (tst--) {
		int roadNum;
		cin >> roadNum;
		int weight;
		string p1, p2;
		places.clear();
		tot = 0;
		for (int i = 0; i < 200; i++)
			for (int j = 0; j < 200; j++)
				if (i != j)
					dis[i][j] = maxn;
				else
					dis[i][j] = 0;
		for (int i = 0; i < roadNum; i++) {
			cin >> p1 >> p2 >> weight;
			if (places.find(p1) == places.end())
				places[p1] = tot++;
			if (places.find(p2) == places.end())
				places[p2] = tot++;
			dis[places[p1]][places[p2]] = weight;
			dis[places[p2]][places[p1]] = weight;
		}
		floyd (tot,dis);
		string S, T;
		cin >> S >> T;
		if (S == T)
			cout << 0 << endl;
		else if (places.find(S) == places.end()
				|| places.find(T) == places.end())
			cout << -1 << endl;
		else {
			int v1 = places[S], v2 = places[T];
			if (dis[v1][v2] >= maxn)
				cout << -1 << endl;
			else
				cout << dis[v1][v2] << endl;
		}
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值