PAT甲级1111 Online Map (30分):[C++题解]两次dijkstra求单源最短路、保存路径、长度最短、时间最短
生活随笔
收集整理的這篇文章主要介紹了
PAT甲级1111 Online Map (30分):[C++题解]两次dijkstra求单源最短路、保存路径、长度最短、时间最短
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 題目分析
- 題目鏈接
題目分析
來源:acwing
分析:dijkstra求單源最短路的題目。 只是寫兩遍而已,第一遍求按照路徑長度求,第二遍按照時間最少求。 另外加一個vector路徑的判斷相等。
輸入輸出有點復雜。
ac代碼
#include<bits/stdc++.h> using namespace std; const int N = 510; bool st[N],st1[N]; int n,m,S, T; //起點和終點路口編號int dist[N]; //長度 int d[N][N],c[N][N];//d是長度, c是時間 int cnt[N]; //統計路口個數 int pre1[N],pre2[N]; int sum[N];// 時間之和 //求距離最短 void dijkstra(){memset(dist, 0x3f, sizeof dist);dist[S] = 0;sum[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[j]<dist[t]))t = j;}st[t] =true;for(int j = 0 ;j < n; j++){if( dist[j] > dist[t] + d[t][j]){dist[j] = dist[t] +d[t][j];//長度更新sum[j] =sum[t] + c[t][j]; //時間更新pre1[j] = t;}else if(dist[j] == dist[t] + d[t][j] && sum[j] > sum[t] + c[t][j]){sum[j] = sum[t] +c[t][j];pre1[j] = t;}} } }//求時間最短 void dijkstra1(){memset(sum, 0x3f, sizeof sum);sum[S] = 0;cnt[S]=1;for(int i = 0; i< n; i++){int t = -1;for( int j =0; j< n; j++){if(!st1[j] &&(t == -1 || sum[j]<sum[t]))t = j;}st1[t] =true;for(int j = 0 ;j < n; j++){if( sum[j] > sum[t] + c[t][j]){sum[j] = sum[t] +c[t][j];//長度更新cnt[j] =cnt[t]+1;pre2[j] = t;}else if(sum[j] == sum[t] + c[t][j] && cnt[j] > cnt[t] + 1){cnt[j] =cnt[t] +1;pre2[j] = t;}}} }int main(){memset(d, 0x3f, sizeof d); //邊的長度,鄰接矩陣存memset(c, 0x3f, sizeof c); //邊的時間,鄰接矩陣存cin >> n >> m;while(m--){ //m個街道int a ,b, flag, length , time1;cin >> a >> b>> flag >> length >>time1;if(flag == 1) //有向邊d[a][b] = min(d[a][b],length),c[a][b] =min(c[a][b],time1);//無向邊else d[a][b] = d[b][a] = min(d[a][b],length),c[a][b]=c[b][a] =min(c[a][b],time1);}cin >> S >> T;//起點和終點dijkstra();//保存路徑vector<int> path1;for(int i = T; i!=S; i =pre1[i]) path1.push_back(i);dijkstra1();vector<int> path;for(int i = T; i!=S; i =pre2[i]) path.push_back(i);//輸出//如果兩個路徑相同if(path1 == path){printf("Distance = %d; Time = %d: ",dist[T],sum[T]);cout<<S;for(int i =path1.size() -1; i>=0 ;i--) cout<<" -> "<<path1[i];cout<<endl;}//不相同else{printf("Distance = %d: ",dist[T]);cout<<S;for(int i =path1.size() -1; i>=0 ;i--) cout<<" -> "<<path1[i];cout<<endl;printf("Time = %d: ",sum[T]);cout<<S;for(int i =path.size() -1; i>=0 ;i--) cout<<" -> "<<path[i];cout<<endl;} }題目鏈接
PAT甲級1111 Online Map (30分)
https://www.acwing.com/problem/content/description/1603/
總結
以上是生活随笔為你收集整理的PAT甲级1111 Online Map (30分):[C++题解]两次dijkstra求单源最短路、保存路径、长度最短、时间最短的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: PAT甲级1087 All Roads
- 下一篇: PAT甲级1122 Hamiltonia