1. 程式人生 > 其它 >最短路刷題

最短路刷題

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=510;
int dist[N],cost[N];
bool st[N];
int n,m,s,d;
struct node
{
    int len,mon;
} g[N][N];
void dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    memset(cost,0x3f,sizeof cost);//要求最小的,所以最開始全部初始化成最大值
dist[s]=0; cost[s]=0; for (int i=0; i<n; i++) { int t=-1; for (int j=0; j<n; j++) { if (!st[j]&&(t==-1||dist[t]>dist[j])) t=j; }//在未確定最小距離的點中找距離集合最近的點 //更新,cost和dist的值要同時更新 for (int j=0; j<n; j++) {
if (!st[j]&&dist[j]>dist[t]+g[t][j].len) { dist[j]=dist[t]+g[t][j].len; cost[j]=cost[t]+g[t][j].mon; } else if (!st[j]&&dist[j]==(dist[t]+g[t][j].len)) { cost[j]=min(cost[j],cost[t]+g[t][j].mon); } } st[t]
=true; } } int main() { cin>>n>>m>>s>>d; memset(g,0x3f,sizeof g);//要求最小的,所以最開始全部初始化成最大值 while (m--) { int s1,s2,len,x; cin>>s1>>s2>>len>>x; g[s1][s2].len=g[s2][s1].len=len; g[s1][s2].mon=g[s2][s1].mon=x; } dijkstra(); cout<<dist[d]<<' '<<cost[d]; return 0; }