您的位置:首页 > 其它

POJ 1502 MPI Maelstrom (Dijkstra)

2016-03-19 14:57 232 查看
题目链接:http://poj.org/problem?id=1502

题意是给你n个点,然后是以下三角的形式输入i j以及权值,x就不算

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAXN = 105;
const int INF = 1e9;
typedef pair <int , int> P;
struct data {
int next , to , cost;
}edge[MAXN * MAXN];
int head[MAXN] , d[MAXN] , cont;
void init(int n) {
for(int i = 1 ; i <= n ; i++) {
head[i] = -1;
d[i] = INF;
}
cont = 0;
}

inline void add(int u , int v , int cost) {
edge[cont].next = head[u];
edge[cont].to = v;
edge[cont].cost = cost;
head[u] = cont++;
}

void dijkstra(int s) {
priority_queue <P , vector<P> , greater<P> > que;
while(!que.empty()) {
que.pop();
}
d[s] = 0;
que.push(P(0 , s));
while(!que.empty()) {
P temp = que.top();
que.pop();
int u = temp.second;
if(d[u] < temp.first)
continue;
for(int i = head[u] ; ~i ; i = edge[i].next) {
int v = edge[i].to;
if(d[v] > d[u] + edge[i].cost) {
d[v] = d[u] + edge[i].cost;
que.push(P(d[v] , v));
}
}
}
}

int main()
{
int n , cost;
while(~scanf("%d" , &n)) {
char str[40];
init(n);
for(int i = 2 ; i <= n ; i++) {
for(int j = 1 ; j < i ; j++) {
scanf("%s" , str);
if(str[0] == 'x')
continue;
int temp = 0;
for(int k = 0 ; str[k] != '\0' ; k++) {
temp = temp * 10 + (str[k] - '0');
}
add(j , i , temp);
add(i , j , temp);
}
}
dijkstra(1);
int res = 0;
for(int i = 1 ; i <= n ; i++) {
res = max(res , d[i]);
}
printf("%d\n" , res);
}
}


,边是双向的,求其中起点到最远的点的最短距离。

直接dijkstra优先队列,速度确实快。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: