poj bfs/dfs求树直径相关之2361 Roads in the North
bfs解法
主要是引进了一个head数组,很方便于记录from节点相同的边有些什么,存在next数组中
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#define MAXNUM 10010
using namespace std;
int N, mark[MAXNUM], head[MAXNUM], dis[MAXNUM], k, sum;
struct Eage
{
int from, to, weight, next;
}links[MAXNUM];
void add(int a, int b, int c)
{
links[k].from = a;
links[k].to = b;
links[k].weight = c;
links[k].next = head[a];
head[a] = k++;
}
int bfs(int a)
{
queue<int> q;
q.push(a);
mark[a] = 1;
int u, v, i, ed;
ed = a;
sum = 0;
while (!q.empty())
{
u = q.front();
q.pop();
for (i = head[u]; i != 0; i = links[i].next)
{
if (!mark[links[i].to])
{
dis[links[i].to] = dis[u] + links[i].weight;
mark[links[i].to] = 1;
q.push(links[i].to);
if (dis[links[i].to] > sum)
{
sum = dis[links[i].to];
ed = links[i].to;
}
}
}
}
return ed;
}
int main()
{
//freopen("1.txt", "r", stdin);
int i, j, t, a, b, c;
k = 1;
memset(head, 0, sizeof(head));
memset(mark, 0, sizeof(mark));
memset(dis, 0, sizeof(dis));
while (scanf("%d%d%d", &a, &b, &c) != EOF)
{
add(a, b, c);
add(b, a, c);
}
t=bfs(1);
memset(mark, 0, sizeof(mark));
memset(dis, 0, sizeof(dis));
bfs(t);
printf("%d\n", sum);
}
dfs:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#include<queue>
#define MAXNUM 10010
using namespace std;
int N, mark[MAXNUM], head[MAXNUM], dis[MAXNUM], k, ed, sum;
struct Eage
{
int from, to, weight, next;
}links[MAXNUM];
void add(int a, int b, int c)
{
links[k].from = a;
links[k].to = b;
links[k].weight = c;
links[k].next = head[a];
head[a] = k++;
}
void dfs(int a)
{
int i, u;
for (i = head[a]; i != 0; i = links[i].next)
{
if (!mark[links[i].to])
{
mark[links[i].to] = 1;
dis[links[i].to] = dis[a] + links[i].weight;
if (dis[links[i].to] > sum)
{
sum = dis[links[i].to];
ed = links[i].to;
}
dfs(links[i].to);
mark[links[i].to] = 0;
}
}
}
int main()
{
//freopen("1.txt", "r", stdin);
int i, j, t, a, b, c;
k = 1;
memset(head, 0, sizeof(head));
memset(mark, 0, sizeof(mark));
memset(dis, 0, sizeof(dis));
while (scanf("%d%d%d", &a, &b, &c) != EOF)
{
add(a, b, c);
add(b, a, c);
}
sum = 0;
ed = 1;
mark[1] = 1;
dfs(1);
memset(mark, 0, sizeof(mark));
memset(dis, 0, sizeof(dis));
sum = 0;
dfs(ed);
printf("%d\n", sum);
}