城市路(信息学奥赛一本通-T1381)
生活随笔
收集整理的這篇文章主要介紹了
城市路(信息学奥赛一本通-T1381)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
【題目描述】
羅老師被邀請參加一個舞會,是在城市n,而羅老師當前所處的城市為1,附近還有很多城市2~n-1,有些城市之間沒有直接相連的路,有些城市之間有直接相連的路,這些路都是雙向的,當然也可能有多條。
現在給出直接相鄰城市的路長度,羅老師想知道從城市1到城市n,最短多少距離。
【輸入】
輸入n, m,表示n個城市和m條路;
接下來m行,每行a b c, 表示城市a與城市b有長度為c的路。
【輸出】
輸出1到n的最短路。如果1到達不了n,就輸出-1。
【輸入樣例】
?5 5
1 2 20
2 3 30
3 4 20
4 5 20
1 5 100
【輸出樣例】
90
【源程序】
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<string> #include<cstdlib> #include<queue> #include<set> #include<vector> #define INF 0x3f3f3f3f #define PI acos(-1.0) #define N 3001 #define MOD 123 #define E 1e-6 using namespace std; struct node{int pre;int next;int w; }a[N*10]; int n,m; int cnt; int head[N],vis[N],f[N]; void add(int x,int y,int w) {cnt++;a[cnt].pre=y;a[cnt].next=head[x];a[cnt].w=w;head[x]=cnt;cnt++;a[cnt].pre=x;a[cnt].next=head[y];a[cnt].w=w;head[y]=cnt; }int main() {cin>>n>>m;for(int i=1;i<=m;i++){int x,y,w;cin>>x>>y>>w;add(x,y,w);}memset(f,INF,sizeof(f));f[1]=0;vis[1]=1;int x=head[1];while(x!=0){int y=a[x].pre;if(f[y]>a[x].w)f[y]=a[x].w;x=a[x].next;}int cnt=0;while(cnt<n){cnt++;int k;int minn=INF;for(int i=1;i<=n;i++)if(vis[i]==0&&f[i]<minn){minn=f[i];k=i;}vis[k]=1;int x=head[k];while(x!=0){int y=a[x].pre;int w=a[x].w;if(vis[y]==0&&f[y]>f[k]+w)f[y]=f[k]+w;x=a[x].next;}}if(f[n]==INF)cout<<"-1"<<endl;elsecout<<f[n]<<endl;return 0; }?
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的城市路(信息学奥赛一本通-T1381)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 均分纸牌(信息学奥赛一本通-T1320)
- 下一篇: 理论基础 —— 二叉树 —— 哈夫曼树与