leetcode 2045. 到達目的地的第二短時間
阿新 • • 發佈:2021-12-10
1 class Solution { 2 public: 3 typedef pair<int,int> pii; 4 struct cmp{ 5 bool operator ()(pii &a,pii &b) 6 { 7 return a.second>b.second; 8 } 9 }; 10 11 int secondMinimum(int n, vector<vector<int>>& edges, inttime, int change) { 12 vector<int>G[n+1]; 13 for(auto &p:edges) 14 { 15 G[p[0]].push_back(p[1]); 16 G[p[1]].push_back(p[0]); 17 } 18 vector<int>dis1(n+1,INT_MAX),dis2(n+1,INT_MAX); 19 priority_queue<pii,vector<pii>,cmp>q;20 q.push({1,0}); 21 int cnt=0,first=INT_MAX; 22 while(q.size()) 23 { 24 auto [u,d]=q.top(); 25 q.pop(); 26 for(int i=0;i<G[u].size();i++) 27 { 28 int v=G[u][i]; 29 int w= (d%(2*change)<change)?d+time:d-(d%(change))+change+time;30 if(w<dis1[v]) 31 { 32 dis2[v]=dis1[v]; 33 dis1[v]=w; 34 q.push({v,w}); 35 } 36 else if(w>dis1[v]&&w<dis2[v]) 37 { 38 dis2[v]=w; 39 q.push({v,w}); 40 } 41 } 42 } 43 return dis2[n]; 44 } 45 };