• 最短路(sp


    #include<stdio.h>
    #include<iostream>
    #include<queue>
    
    using namespace std;
    
    #define N 205
    #define INF 99999999
    
    int n,m,map[N][N];
    int visited[N],dis[N];
    
    int SPFA(int src,int des){
        int i;
        for(i=0;i<n;i++){
            dis[i]=INF;
            visited[i]=0;
        }
        queue<int> myqueue;
        while(!myqueue.empty())
            myqueue.pop();
        dis[src]=0;
        visited[src]=1;
        myqueue.push(src);
        int tmp;
        while(!myqueue.empty()){
            tmp=myqueue.front();
            myqueue.pop();
            visited[tmp]=0;
            for(i=0;i<n;i++)
                if(dis[i]>dis[tmp]+map[tmp][i]){
                    dis[i]=dis[tmp]+map[tmp][i];
                    if(!visited[i]){
                        visited[i]=1;
                        myqueue.push(i);
                    }
                }
        }
        return dis[des];
    }
    
    int main(){
        int u,v,cost;
        while(scanf("%d%d",&n,&m)!=EOF){
            int i,j;
            for(i=0;i<n;i++)
                for(j=0;j<n;j++)
                    map[i][j]=INF;
            for(i=0;i<m;i++){
                scanf("%d%d%d",&u,&v,&cost);
                if(cost<map[u][v])
                    map[u][v]=map[v][u]=cost;
            }
            int s,t;
            scanf("%d%d",&s,&t);
            int ans=SPFA(s,t);
            if(ans<INF)
                printf("%d
    ",ans);
            else
                printf("-1
    ");
        }
        return 0;
    }
    View Code
  • 相关阅读:
    有一种尺度叫圆融
    十大经典排序算法
    Maximal Square
    Word Break
    Flatten List
    Triangle
    Paint Fence
    Longest Increasing Continuous Subsequence
    Minimum Size Subarray Sum
    Letter Combinations of a Phone Number
  • 原文地址:https://www.cnblogs.com/DWVictor/p/10294700.html
Copyright © 2020-2023  润新知