标签:最短路 name jks -- printf tin ons 无向图 int
题目:洛谷P2951。
题目大意:给你一张无向图,让你找从1出发到其他点的最短路径中,最长的是多少,以及这个点的最小编号,和一共有几个这样的最短路径。
解题思路:跑一遍最短路,然后处理即可。我用的是堆优化Dijkstra。
C++ Code:
#include<cstdio> #include<ext/pb_ds/priority_queue.hpp> #include<vector> #include<cstring> #include<algorithm> using namespace std; struct edge{ int from,to,dist; }; vector<edge>G[80000]; int n,m,d[22222]; struct heapnode{ int u,d; bool operator<(const heapnode&$)const{return d>$.d;} }; __gnu_pbds::priority_queue<heapnode>q; inline void addedge(int from,int to){ G[from].push_back((edge){from,to,1}); G[to].push_back((edge){to,from,1}); } void dijkstra(int s){ memset(d,0x3f,sizeof d); q.push((heapnode){s,d[s]=0}); while(!q.empty()){ heapnode x=q.top(); q.pop(); int u=x.u; if(d[u]!=x.d)continue; for(int i=0;i<G[u].size();++i){ edge& e=G[u][i]; if(d[e.to]>d[u]+e.dist){ d[e.to]=d[u]+e.dist; q.push((heapnode){e.to,d[e.to]}); } } } } int main(){ scanf("%d%d",&n,&m); while(m--){ int x,y; scanf("%d%d",&x,&y); addedge(x,y); } dijkstra(1); int far=*max_element(d+2,d+n+1),cnt=0,num; for(int i=n;i>1;--i) if(d[i]==far){ ++cnt; num=i; } printf("%d %d %d\n",num,far,cnt); return 0; }
标签:最短路 name jks -- printf tin ons 无向图 int
原文地址:http://www.cnblogs.com/Mrsrz/p/7402500.html