zoukankan      html  css  js  c++  java
  • 1874 Bellman-ford算法 队列优化过的 用于稀疏图,有负权的图

    #include<stdio.h>
    #include<algorithm>
    #include<iostream>
    #include<queue>
    using namespace std;
    #define N  2100
    struct node {
    int u,v,w,next;
    }bian[N];
    int n,m,yong,head[N];
    void creat(int u,int v,int w) {
    bian[yong].u=u;
    bian[yong].v=v;
    bian[yong].w=w;
    bian[yong].next=head[u];
    head[u]=yong++;
    }
    void Dcreat(int u,int v,int w) {
    creat(u,v,w);
    creat(v,u,w);
    }
    int Bellman-ford(int u,int s) {
    int cur,dis[N],i,visit[N],v;
    queue<int>q;
    memset(visit,0,sizeof(visit));
    for(i=0;i<n;i++)
    dis[i]=1000000000;
    dis[u]=0;
    q.push(u);
    visit[u]=1;
    while(!q.empty()) {
    u=q.front();
    q.pop();
             visit[u]=0;
    for(i=head[u];i!=-1;i=bian[i].next) {
    v=bian[i].v;
    if(dis[v]>bian[i].w+dis[u]) {
    dis[v]=bian[i].w+dis[u];
    if(!visit[v]) {
    visit[v]=1;            
    q.push(v);
    }                     
    }
    }
    }
    for(i=0;i<yong;i++)//判断是否存在负权路
    if(dis[bian[i].v]>dis[bian[i].u]+bian[i].w)//
    return -1;
    if(dis[s]<1000000000)
    return dis[s];
    return -1;
    }
    int main() {
    int a,b,k;
    while(scanf("%d%d",&n,&m)!=EOF) {
    yong=0;
    memset(head,-1,sizeof(head));
    while(m--) {
    scanf("%d%d%d",&a,&b,&k);
    Dcreat(a,b,k);
    }
    scanf("%d%d",&a,&b);
    printf("%d ",Bellman-ford(a,b));
    }
    return 0;
    }
  • 相关阅读:
    BZOJ4223 : Tourists
    BZOJ3565 : [SHOI2014]超能粒子炮
    BZOJ3499 : PA2009 Quasi-template
    BZOJ3490 : Pa2011 Laser Pool
    BZOJ2828 : 火柴游戏
    BZOJ3070 : [Pa2011]Prime prime power 质数的质数次方
    BZOJ2138 : stone
    BZOJ2167 : 公交车站
    BZOJ1290 : [Ctsc2009]序列变换
    Ural2110 : Remove or Maximize
  • 原文地址:https://www.cnblogs.com/thefirstfeeling/p/4410865.html
Copyright © 2011-2022 走看看