Cow Marathon
Time Limit: 2000MS | Memory Limit: 30000K | |
Total Submissions: 2672 | Accepted: 1317 | |
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
题意:
找出农场中最长的路径,即直径。
题目不难,两次DFS就搞定了。不过图的存储方式应该要用邻接表,这样,在DFS时,会比较节省时间。
首先,根据:在图上任意一点的距离最远的点一定是最长路径端点中的一点。所以先由任意一点出发,找到距离其最长的点;然后再由该点出发,找到距离该点最长的点。两点之间的距离即所求的最长距离。
代码实现:
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
#define maxver 100010
#define maxpoint 100010
int first[maxpoint];
int w[maxver];
int next[maxver];
int v[maxver];
int d[maxpoint];
int vis[maxpoint];
int dfs(int start,int len){
if(d[start]<len)
d[start]=len;
vis[start]=1;
for(int h=first[start];h!=-1;h=next[h]){
if(vis[v[h]]==0){
dfs(v[h],len+w[h]);
}
}
}
int main(){
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){ //cin the number of point and ver
memset(first,-1,sizeof(first));
memset(next,-1,sizeof(next));
memset(vis,0,sizeof(vis));
memset(d,-1,sizeof(d));
for(int i=1;i<=m;i++){
int temp1,temp2;
char s[16];
scanf("%d%d%d%s",&temp1,&temp2,&w[i],s); //cin the ver's points and weigh
if(first[temp1]==-1){
first[temp1]=i;
}
else{
int temp3=first[temp1];
first[temp1]=i;
next[i]=temp3;
}
v[i]=temp2;
if(first[temp2]==-1)
first[temp2]=i+n;
else{
int tmp=first[temp2];
first[temp2]=i+n;
next[i+n]=tmp;
}
v[i+n]=temp1;
w[i+n]=w[i];
}
dfs(1,0);
int rele=-1;
int end;
for(int k=1;k<=n;k++){
if(rele<d[k]){
rele=d[k];
end=k;
}
}
memset(vis,0,sizeof(vis));
memset(d,-1,sizeof(d));
dfs(end,0);
int maxn=-1;
for(int f=1;f<=n;f++){
if(maxn<d[f])
maxn=d[f];
}
printf("%d\n",maxn);
}
return 0;
}
该题还可以用树状DP来求解,并且耗时会减小,该方法暂时没掌握,知道了再来更新。