[dijkstra] 1030 Travel Plan 笔记

本文深入探讨了使用C++实现图算法的过程,包括初始化图结构、应用深度优先搜索(DFS)进行路径查找,并通过具体代码示例展示了如何计算最短距离和最低成本路径。文章分析了代码中常见的错误,如变量名误用、边界条件处理不当等问题。

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

#include <iostream>
#include <sstream>
#include <string>
#include <sstream>
#include <cstdio>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <map>
#include <queue>
#include <set>
#define maxm 1010
#define inf 0x3fffffff
using namespace std;

int G[maxm][maxm];
int cost[maxm][maxm];
int dist[maxm]={0};
bool vis[maxm]={false};
int mcost[maxm]={0};
int path[maxm];

void DFS(int o,int s){
    if(o==s){
        printf("%d ",s);
        return;
    }
    int t=path[o];
    DFS(t,s);
    printf("%d ",o);
}

int main()
{
    fill(G[0],G[0]+maxm*maxm,inf);
    fill(cost[0],cost[0]+maxm*maxm,inf);
    fill(dist,dist+maxm,inf);
    fill(mcost,mcost+maxm,inf); //error mcost not cost
    int n,m,s,o;
    cin>>n>>m>>s>>o;
    int a,b,d,c;
    dist[s]=0;   //s not 0
    mcost[s]=0;     //error mcost not cost
    for(int i=0;i<n;i++)path[i]=i;
    for(int i=0; i<m; i++)
    {
        scanf("%d%d%d%d",&a,&b,&d,&c);
        G[a][b]=G[b][a]=d;    //G[b][a]==d?
        cost[a][b]=cost[b][a]=c;
    }
    for(int x=0; x<n; x++)  //dont't left it
    {
        int v=-1,mw=inf;
        for(int i=0; i<n; i++)
        {
            if(vis[i]==false&&dist[i]<mw)
            {
                mw=dist[i];
                v=i;
            }
        }
        if(v==-1)break;
        vis[v]=true;
        for(int i=0; i<n; i++)
        {
            if(vis[i]==false&&G[v][i]!=inf)
            {
                if(dist[i]>dist[v]+G[v][i])
                {
                    dist[i]=dist[v]+G[v][i];
                    mcost[i]=mcost[v]+cost[v][i];
                    path[i]=v;
                }
                else if(dist[i]==dist[v]+G[v][i]&&mcost[i]>mcost[v]+cost[i][v])
                {
                    mcost[i]=mcost[v]+cost[i][v];
                    path[i]=v;
                }
            }
        }
    }
    DFS(o,s);
    cout<<dist[o]<<" "<<mcost[o]; //mcost not cost

    return 0;
}

总结:低级错误很多,看看错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值