最短路例题

Floyd求最短路

例题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1874

#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
const int inf = 0x3f3f3f3f;
const int mod = 998244353;
const int N = 5000005;
const ll ds = 1e15+7;
//const double p1 = 3.141592653589793238462643383;

using namespace std;

int n,m;
int ans[505][505];
void solve()
{
	for(int i = 0; i <= n; i++){
		for(int j = 0; j <= n; j++){
			if(i == j) ans[i][j] = 0;
			else ans[i][j] = 1e9;
		}
	}
	for(int i = 1; i <= m; i++){
		int a,b,x;
		cin >> a >> b >> x;
		if(ans[a][b] > x) ans[a][b] = x;
		if(ans[b][a] > x) ans[b][a] = x;
	}
	int s,t;
	cin >> s >> t;
	for(int k = 0; k < n; k++){
		for(int i = 0; i < n; i++){
			if(ans[i][k] != 1e9)
				for(int j = 0; j < n; j++){
					if(ans[i][j] > ans[i][k]+ans[k][j]) 
						ans[i][j] = ans[i][k]+ans[k][j];
				}
		}
	}
	if(ans[s][t] == 1e9) cout << "-1\n";
	else cout << ans[s][t] << endl;
}  

int main()
{
	while(~scanf("%d%d",&n,&m)){
		solve();
	}	
	return 0;
}

例题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1596

#include <bits/stdc++.h>
#define ull unsigned long long
#define ll long long
const int inf = 0x3f3f3f3f;
const int mod = 998244353;
const int N = 5000005;
const ll ds = 1e15+7;
//const double p1 = 3.141592653589793238462643383;

using namespace std;

int n;
double ans[1005][1005];
void solve()
{
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
           	scanf("%lf",&ans[i][j]);
        }
    }
    int s,t;
    for(int k = 0; k < n; k++){
        for(int i = 0; i < n; i++){
            if(ans[i][k] != 0)
                for(int j = 0; j < n; j++){
                 	   if(ans[i][j] < ans[i][k]*ans[k][j]) 
                     	   ans[i][j] = ans[i][k]*ans[k][j];
                }
        }
    }
    int q;
    scanf("%d",&q);
    while(q--){
    	scanf("%d%d",&s,&t);
    	if(ans[s-1][t-1] == 0) printf("What a pity!\n");
  		else printf("%.3f\n",ans[s-1][t-1]);
	}
}  

int main()
{
    while(~scanf("%d",&n)){
        solve();
    }    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值