POJ 1985 Cow Marathon

Description
After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.


【题目分析】
    树上最长路,两侧bfs就可以解决。
   


【代码】

#include <queue>
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
typedef struct{
    int t,w,next;
}Edge;
Edge edge[100001];
int n,m,e,head[50001],record[50001];
void addedge(int s,int t,int w){
    edge[e].t=t;
    edge[e].w=w;
    edge[e].next=head[s];
    head[s]=e++;
}
int bfs(int s,int flag){
    int i,v,t;
    int tmp=0,tmpi=s;
    queue <int>q;
    memset(record,-1,sizeof(record));
    record[s]=0;
    q.push(s);
    while(!q.empty()){
        v=q.front();q.pop();
        for(i=head[v];i!=-1;i=edge[i].next){
            t=edge[i].t;
            if(record[t]==-1){
                record[t]=record[v]+edge[i].w;
                if(record[t]>tmp){
                    tmp=record[t];
                    tmpi=t;
                }
                q.push(t);
            }
        }
    }
    return flag?tmpi:tmp;
}
int main(){
    int a,b,w,ans;
    char c;
    scanf("%d%d\n",&n,&m);
    memset(head,-1,sizeof(head));
    e=0;
    while(m--){
        scanf("%d %d %d %c\n",&a,&b,&w,&c);
        addedge(a,b,w);
        addedge(b,a,w);
    }
    a=bfs(1,1);
    ans=bfs(a,0);
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值