HDU 2544 最短路 SPFA

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2544

DFS版本
代码:

#include 
#define sf scanf
#define pf printf
using namespace std;
const int maxn = 105,maxm = 10000 + 50;
struct Edge{
    int v,c,pre;
}Es[maxm * 2];
int head[maxn],tot;
void EDGE_INIT(){
    memset(head,-1,sizeof head),tot = 0;
}
void ADD_EDGE(int u,int v,int c){
    Es[tot].v = v;
    Es[tot].c = c;
    Es[tot].pre = head[u];
    head[u] = tot++;
}

int d[maxn],vis[maxn];
void DFS(int u){
    vis[u] = 1;
    for(int i = head[u];~i;i = Es[i].pre){
        int v = Es[i].v,c = Es[i].c;
        if(d[v] > d[u] + c){
            d[v] = d[u] + c;
            if(!vis[v]) DFS(v);
        }
    }
    vis[u] = 0;
}

int main(){
    int n,m;
    while(sf("%d%d",&n,&m)){
        if(!n && !m) break;
        memset(d,0x3f,sizeof d);
        EDGE_INIT();
        for(int i = 0;i < m;++i){
            int u,v,c;sf("%d%d%d",&u,&v,&c);
            ADD_EDGE(u,v,c);
            ADD_EDGE(v,u,c);
        }
        d[1] = 0;
        DFS(1);
        pf("%d\n",d[n]);
    }
    return 0;
}

你可能感兴趣的:(-----------,算法,----------,图论,图论,--------,最短路)