poj1797最短路变形

本文介绍了如何解决POJ1797这个问题,通过解析题目需求,采用最短路算法进行求解。文章详细探讨了算法的实现细节,包括关键步骤的优化策略,帮助读者理解如何在实际问题中应用最短路算法。

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



#include<iostream>
#include<cstdio>
#include<queue>
#include<string.h>
using namespace std;
int t,n,m;
const int maxn = 1e3+10;
int mp[maxn][maxn];
const int inf = 0x3f3f3f3f;
struct Edge{
    int to,w,next;
    bool operator < (const Edge &a) const{
        return a.w<w;
    }
    Edge(int _to=0,int _w=0,int _next=0):to(_to),w(_w),next(_next){}
}edge[maxn+100000];
int cnt = 0;
int head[maxn+100000];
int dist[maxn];
int vis[maxn];
int pre[maxn];
int maxs[maxn];
int st,ed;
void init(){
    memset(head,-1,sizeof(head));
    cnt = 0;
    st = 1;
    ed = n;
}
void addedge(int u,int v,int w){
    edge[cnt].to = v;
    edge[cnt].w = w;
    edge[cnt].next = head[u];
    head[u] = cnt++;
}
struct node{
    int r,c;
    bool operator < (const node &r) const{
        return c<r.c;
    }
    node(int _r,int _c):r(_r),c(_c){}

};
void diji(){
    memset(pre,-1,sizeof(pre));
    memset(vis,0,sizeof(vis));
    for(int i =1;i<=n;++i)dist[i] =inf;
    dist[st] = inf;
    priority_queue<node>q;
    q.push(node(st,inf));
    while(!q.empty()){
        node t = q.top();
        q.pop();
        int u = t.r;
        //cout<<u<<endl;
        if(vis[u])continue;
        vis[u] = 1;
        for(int i = head[u];~i;i = edge[i].next){
            int to = edge[i].to;
            int w = edge[i].w;
            //cout<<"to"<<to<<"w:"<<w<<endl;
            if(!vis[to]&&(dist[to]<min(dist[u],w)||dist[to]==inf)){
                dist[to]=min(dist[u],w);
                q.push(node(to,dist[to]));
            }
        }
    }

}

int main(){
    scanf("%d",&t);
    int cnt = 1;
    while(t--){
        scanf("%d%d",&n,&m);
        init();
        for(int i =0;i<m;++i){
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            addedge(u,v,w);
            addedge(v,u,w);
        }

        diji();
        printf("Scenario #%d:\n",cnt++);
        printf("%d\n",dist[n]);
        if(t!=0)cout<<endl;


    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值