码迷,mamicode.com
首页 > 其他好文 > 详细

BZOJ 3361 [Usaco2004 Jan]培根距离

时间:2017-09-15 02:00:35      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:pre   space   while   node   spfa   clu   false   cst   scan   

SPFA裸题,练手练手~

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <queue>

using namespace std;
int const maxn = 2*10005;

struct node{
    int u,v,w,next;
    node(){}
    node(int _u,int _v,int _w,int _next){
        u = _u;
        v = _v;
        w = _w;
        next = _next;
    }
}Edge[maxn];

int n,p;
int head[maxn],Count;
int toque[maxn],dis[maxn];
bool inque[maxn];

void AddEdge(int u,int v,int w){
    Count++;
    Edge[Count] = node(u,v,w,head[u]);
    head[u] = Count;
}

bool spfa(){
    dis[1]=0;
    queue<int>Q;
    Q.push(1);
    inque[1]=true;
    while( !Q.empty() ){
        int now = Q.front();
        Q.pop();
        inque[now]=false;
        toque[now]++;
        if(toque[now]>=n) return false;
        for(int i=head[now];i;i=Edge[i].next){
            int w = Edge[i].w;
            int v = Edge[i].v;
            if(dis[now]+w<dis[v]){
                dis[v] = dis[now]+w;
                if(!inque[v]){
                    Q.push(v);
                    inque[v] = true;
                }
            }
        }
    }
    return false;
}

int main(){
    memset(dis,0x3f3f3f3f,sizeof(dis));
    scanf("%d%d",&n,&p);
    for(int i=1;i<=p;i++){
        int x,y;
        scanf("%d%d",&x,&y);
        AddEdge(x,y,1);
        AddEdge(y,x,1);
    }
    spfa();
    int Max = -1;
    for(int i=1;i<=n;i++) Max = max(Max,dis[i]);
    printf("%d\n",Max);
    return 0;
}

 

BZOJ 3361 [Usaco2004 Jan]培根距离

标签:pre   space   while   node   spfa   clu   false   cst   scan   

原文地址:http://www.cnblogs.com/OIerLYF/p/7523859.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!