Cow Marathon
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 3355 | Accepted: 1697 | |
Case Time Limit: 1000MS |
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.
Input
* Lines 1.....: Same input format as "Navigation Nightmare".
Output
* Line 1: An integer giving the distance between the farthest pair of farms.
Sample Input
7 6 1 6 13 E 6 3 9 E 3 5 7 S 4 1 3 N 2 4 20 W 4 7 2 S
Sample Output
52
Hint
The longest marathon runs from farm 2 via roads 4, 1, 6 and 3 to farm 5 and is of length 20+3+13+9+7=52.
Source
第一次这么保存图结构(邻接表表示):对于u-->v,边是和v绑定的,next指向下一条边,adj[u]指向和u相连的众多边的一个边的一个点,存图的代码如下:
void add(int u,int v,int w){//u-->v
edges[e].v=v;
edges[e].w=w;
edges[e].next=adj[u]; //边的下标
adj[u]=e; //边的下标
e++;
}
全部代码为
//一个bug:root没有初始化
#include<iostream>
#include<stdio.h>
#include<string.h>
#define MAX 40005
using namespace std;
struct edge{
int v;
int next;
int w;
}edges[4000500];
int dis[MAX]={0};
int vis[MAX]={0};
int adj[MAX]={-1};
int e=0;
void add(int u,int v,int w){//u-->v
edges[e].v=v;
edges[e].w=w;
edges[e].next=adj[u]; //边的下标
adj[u]=e; //边的下标
e++;
}
void dfs(int s,int l){
int i;
vis[s]=1;
if(l>dis[s]){
dis[s]=l;
}
for(i=adj[s];i!=-1;i=edges[i].next){
if( !vis[ edges[i].v ] ){
dfs( edges[i].v ,l+edges[i].w );
}
}
}
int main(){
int n,m,i,j,first,u,v,w,second;
char ch[5];
scanf("%d%d",&n,&m);
memset(adj,-1,sizeof(adj));//sizeof(dis)位置写成3*n属于脑残型范2
for(i=0;i<m;i++){
scanf("%d%d%d%s",&u,&v,&w,ch);
add(u,v,w);
add(v,u,w);
}
dfs( edges[e-1].v ,0);
int root=1;
int max=dis[1];
for(i=2;i<=n;i++){
if(dis[i]>max){
max=dis[i];
root=i;
}
}
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
dfs( root , 0);
max=dis[1];
for(i=2;i<=n;i++){
if(dis[i]>max){
max=dis[i];
root=i;
}
}
printf("%d\n",max);
/*
for(i=1;i<=n;i++){//这种存法来判断是否为叶子节点
if( edges[ adj[i] ].next!=-1 )
dis[ i ]=0;
}
first=max(dis[1],dis[2]);
second=min(dis[1],dis[2]);
for(i=3;i<=n;i++)
if(dis[i]>first){
second=first;
first=dis[i];
}
if( edges[ adj[ edges[e-1].v ] ].next!=-1 )
printf("%d\n",first+second);
else{
printf("%d\n",first);
}
*/
return 0;
}
第二次dfs前居然root没有初始化,调试了很久都不知道哪wa了;另外,至今没有彻底想明白为什么注释部分判断叶子的方法有什么问题,求大牛指教