POJ 1502 MPI Maelstrom(Dijkstra)
http://poj.org/problem?id=1502
题意:
(整个第一段题意描述都是无关的话,可以直接看input)题目的输入给了你一个n个节点的无向图的邻接矩阵的下三角部分.要求你输出从第0个点到所有其他点的距离的最大值.
分析:
Dijkstra入门题,直接用刘汝佳的模板处理即可.
AC代码:
#include<cstdio> #include<cstring> #include<vector> #include<queue> using namespace std; const int maxn = 100+5; #define INF 1e8 int n; struct Edge { int from,to,dist; Edge(){} Edge(int f,int t,int d):from(f),to(t),dist(d){} }; struct HeapNode { int d,u; HeapNode(){} HeapNode(int d,int u):d(d),u(u){} bool operator < (const HeapNode &rhs)const { return d > rhs.d; } }; struct Dijkstra { int n,m; vector<Edge> edges; vector<int> G[maxn]; bool done[maxn]; int d[maxn]; int p[maxn]; void init(int n) { this->n=n; for(int i=0;i<n;i++) G[i].clear(); edges.clear(); } void AddEdge(int from,int to,int dist) { edges.push_back(Edge(from,to,dist) ); m = edges.size(); G[from].push_back(m-1); } void dijkstra(int s) { priority_queue<HeapNode> Q; for(int i=0;i<n;i++) d[i]=INF; d[s]=0; memset(done,0,sizeof(done)); Q.push(HeapNode(0,s) ); while(!Q.empty()) { HeapNode x=Q.top(); Q.pop(); int u=x.u; if(done[u]) continue; done[u]= true; for(int i=0;i<G[u].size();i++) { Edge& e= edges[G[u][i]]; if(d[e.to]> d[u]+e.dist) { d[e.to] = d[u]+e.dist; p[e.to] = G[u][i]; Q.push(HeapNode(d[e.to],e.to) ); } } } } }DJ; int main() { while(scanf("%d",&n)==1) { DJ.init(n); for(int i=1;i<n;i++) for(int j=0;j<i;j++) { char str[10]; int d; scanf("%s",str); if(str[0]!='x') { sscanf(str,"%d",&d); DJ.AddEdge(i,j,d); DJ.AddEdge(j,i,d); } } DJ.dijkstra(0); int max_v=-1; for(int i=0;i<n;i++) max_v = max(max_v,DJ.d[i]); printf("%d\n",max_v); } return 0; }