POJ 1502 Dijkstra 矩阵存图 priority

本文介绍了一种使用矩阵实现Dijkstra算法的方法,并通过一个具体的模板题进行了解释说明。该方法利用邻接矩阵而非常见的邻接表来实现,提供了一个不同于传统前向星存储结构的实现思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//比较好的一个模板题,原来的Dijkstra + priority一直用邻接前向星实现
//这道题尝试用矩阵实现,也成功了
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<algorithm>
using namespace std;
const int maxv=509;
const int INF=0x3f3f3f3f;
int mmap[maxv][maxv],dis[maxv];
bool visit[maxv];
void init() {
    memset(mmap,INF,sizeof mmap);
    memset(dis,INF,sizeof dis);
}
struct Node{
    int u,dis;
    bool operator< (const Node rhs) const{
        return this->dis>rhs.dis;
    }
}now,temp;
void Dijkstra(int s,int n,int mmap[][maxv],int dist[maxv],bool visit[]) {
    int i,v;
    dist[s]=0;
    priority_queue<Node> pq;
    temp.dis=0,temp.u=s;
    pq.push(temp);
    while(!pq.empty()) {
        temp=pq.top();
        pq.pop();
        if(visit[temp.u]==true)
            continue;
        visit[temp.u]=true;
        for(v=1;v<=n;v++){
            if(visit[v]==false&&dist[v]>dist[temp.u]+mmap[temp.u][v]){
                dist[v]=dist[temp.u]+mmap[temp.u][v];
                now.u=v;
                now.dis=dist[v];
                pq.push(now);
            }
        }
    }
}
int main(void) {
#ifndef ONLINE_JUDGE
    freopen("E:\\input.txt","r",stdin);
#endif // ONLINE_JUDGE
    ios::sync_with_stdio(false);
    int n,temp_int;
    char temp[10];
    cin>>n;
    init();
    for(int i=2; i<=n; i++)
        for(int j=1; j<i; j++) {
            cin>>temp;
            if(temp[0]=='x')
                mmap[i][j]=mmap[j][i]=INF;
            else {
                sscanf(temp,"%d",&temp_int);
                mmap[i][j]=mmap[j][i]=temp_int;
            }
        }
    Dijkstra(1,n,mmap,dis,visit);
    int ans=*(max_element(dis+1,dis+1+n));
    cout<<ans<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值