图的直径

求法:任意一个点A到它的最远点B的距离为半径,B再到它的最远点C的距离为直径。


#include
#include
using namespace std;
class Node
{
public:
 	Node(int i, int w) :index(i), weight(w)
 	{
 	}
 	int index;
 	int weight;
};
vector<Node> v[51];
int max = 0;
int point = 0;
void dfs(int now,int pre,int sum)
{
 	bool flag = true;
 	int len = v[now].size();
 	int next,dis;
 	for (int i = 0; i < len; ++i)
 	{
  		next = v[now][i].index;
  		dis = v[now][i].weight;
  		if (next == pre) continue;
  		flag = false;
  		dfs(next, now, sum + dis);
 	}
 	if (flag) //叶子节点了
 	{
  		if (max < sum)
  		{
   			max = sum; point = now;
  		}
 	}
}
int main(void)
{
	int n, m;
 	cin >> n >> m;
 	int f, t, w;
 	for (int i = 0; i < m; ++i)
 	{
  		cin >> f >> t >> w;
  		v[f].push_back(Node(t, w));
  		v[t].push_back(Node(f, w));
 	}
 	dfs(1, 0, 0);
 	dfs(point, 0, 0);
 	cout << max << endl;
 	
	return 0;
}

你可能感兴趣的:(算法)