当前位置: 代码迷 >> 综合 >> HDU 1874 通畅工程续(Dijkstra)
  详细解决方案

HDU 1874 通畅工程续(Dijkstra)

热度:23   发布时间:2023-12-08 11:20:19.0

题目链接:HDU 1874

分析:直接套模版即可。

CODE:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;const int maxint=999999;
const int maxnum=100;int dist[maxnum];
int pre[maxnum];
int c[maxnum][maxnum];
int n,line;void Dijkstra(int n,int v,int *dist,int *pre,int c[maxnum][maxnum])
{int s[maxnum];for(int i=0;i<n;i++){dist[i]=c[v][i];s[i]=0;if(dist[i]==maxint) pre[i]=0;else pre[i]=v;}dist[v]=0;s[v]=1;for(int i=1;i<n;i++){int tmp=maxint;int u=v;for(int j=0;j<n;j++)if((!s[j])&&dist[j]<tmp){u=j;tmp=dist[j];}s[u]=1;for(int j=0;j<n;j++){if((!s[j])&&c[u][j]<maxint){int newdist=c[u][j]+dist[u];if(newdist<dist[j]){dist[j]=newdist;pre[j]=u;}}}}
}int main()
{
#ifdef LOCALfreopen("in.txt","r",stdin);//freopen("out.txt","w",stdout);
#endif while(cin>>n>>line){for(int i=0;i<n;i++)for(int j=0;j<n;j++)c[i][j]=maxint;int p,q,len;for(int i=1;i<=line;i++){cin>>p>>q>>len;if(len<c[p][q]){c[p][q]=len;c[q][p]=len;}}int start,end;cin>>start>>end;for(int i=0;i<n;i++)dist[i]=maxint;Dijkstra(n,start,dist,pre,c);if(dist[end]==maxint) cout<<-1<<endl;else cout<<dist[end]<<endl;}return 0;
}


  相关解决方案