时间限制:1.0s 内存限制:128.0MB
问题描述
给定一个n节点m边的无圈且连通的图,求直径
输入格式
第一行两个数字n,m
接下来m行每行两个数字x,y,代表x,y之间有一条边
输出格式
要求用户的输出满足的格式。
例:输出1行,包含一个整数,表示矩阵中所有元素的和。
样例输入
一个满足题目要求的输入范例。
3 2
1 2
2 3
样例输出
与上面的样例输入对应的输出。
例:
2
数据规模和约定
- 数据不会很大
- 输入数据满足M=N-1
解题报告
很明显题目给的图是树,求树的直径大小:从任一节点出发找最远的点,再求该点出发离最远的点的距离,所得为所求。
因为题目没给数据范围,用了new,打了一遍Dijstra算法,再复制一份(有点笨的做法)
#include<bits/stdc++.h>
using namespace std;
const int inf=0x3f3f3f3f;
int n,m;
int cnt=0;
struct cmp {
bool operator() (pair<int,int> a,pair<int,int> b) {
return a.first>b.first;
}
};
int main()
{
cin>>n>>m;
int *net=new int[2*n+5],*v=new int[2*n+5];
int *head=new int[n+5],*dis=new int[n+5],*vis=new int[n+5];
for(int i=1;i<=n;i++) {
head[i]=-1;
}
for(int i=1;i<=m;i++) {
int a,b;
cin>>a>>b;
net[++cnt]=head[a];
head[a]=cnt;
v[cnt]=b;
net[++cnt]=head[b];
head[b]=cnt;
v[cnt]=a;
}
for(int i=2;i<=n;i++)
dis[i]=inf,vis[i]=false;
dis[1]=0;
priority_queue<pair<int,int>,vector<pair<int,int> >,cmp>que;
que.push(make_pair(dis[1],1));
while(!que.empty()) {
pair<int,int> p=que.top();
que.pop();
int u=p.second;
if(vis[u]) continue;
vis[u]=true;
for(int i=head[u];~i;i=net[i]) {
int d=p.first;
int ed=v[i];
if(!vis[ed]&&dis[ed]>dis[u]+1) {
dis[ed]=dis[u]+1;
que.push(make_pair(dis[ed],ed));
}
}
}
int maxn=0,pos=0;
for(int i=2;i<=n;i++) {
if(dis[i]>maxn) {
maxn=dis[i];
pos=i;
}
}
for(int i=1;i<=n;i++)
dis[i]=inf,vis[i]=false;
dis[pos]=0;
que.push(make_pair(dis[pos],pos));
while(!que.empty()) {
pair<int,int> p=que.top();
que.pop();
int u=p.second;
if(vis[u]) continue;
vis[u]=true;
for(int i=head[u];~i;i=net[i]) {
int d=p.first;
int ed=v[i];
if(!vis[ed]&&dis[ed]>dis[u]+1) {
dis[ed]=dis[u]+1;
que.push(make_pair(dis[ed],ed));
}
}
}
maxn=0;
for(int i=1;i<=n;i++) {
if(dis[i]>maxn)
maxn=dis[i];
}
cout<<maxn;
return 0;
}