湫湫系列故事——设计风景线
Problem Description
随着杭州西湖的知名度的进一步提升,园林规划专家湫湫希望设计出一条新的经典观光线路,根据老板马小腾的指示,新的风景线最好能建成环形,如果没有条件建成环形,那就建的越长越好。
现在已经勘探确定了n个位置可以用来建设,在它们之间也勘探确定了m条可以设计的路线以及他们的长度。请问是否能够建成环形的风景线?如果不能,风景线最长能够达到多少?
其中,可以兴建的路线均是双向的,他们之间的长度均大于0。
Input
测试数据有多组,每组测试数据的第一行有两个数字n, m,其含义参见题目描述;
接下去m行,每行3个数字u v w,分别代表这条线路的起点,终点和长度。
[Technical Specification]
1. n<=100000
2. m <= 1000000
3. 1<= u, v <= n
4. w <= 1000
Output
对于每组测试数据,如果能够建成环形(并不需要连接上去全部的风景点),那么输出YES,否则输出最长的长度,每组数据输出一行。
Sample Input
3 3
1 2 1
2 3 1
3 1 1
Sample Output
YES
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define K 100011
using namespace std;
struct node{
int fo,to,val,next;
}st[K*20];
bool vis[K],H;
int dis[K],num;
int head[K];
int bo[K];
int N,M,ans,cot;
void add(int x,int y,int z)
{
node E={x,y,z,head[x]};
st[num]=E;
head[x]=num++;
}
void BFS(int fx)
{
queue <int> q;
while(!q.empty())
q.pop();
memset(dis,0,sizeof(dis));
memset(vis,false,sizeof(vis));
vis[fx]=true;
ans=0;
cot=fx;
q.push(fx);
while(!q.empty())
{
int w=q.front();
q.pop();
for(int i=head[w];i!=-1;i=st[i].next)
{
node E=st[i];
if(!vis[E.to]&&dis[E.to]<E.val+dis[w])
{
vis[E.to]=true;
dis[E.to]=E.val+dis[w];
if(dis[E.to]>ans)
{
ans=dis[E.to];
cot=E.to;
}
q.push(E.to);
}
}
}
}
int find(int p)
{
int ch=p;
int t;
while(p!=bo[p])
p=bo[p];
return p;
}
void KL(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
bo[fy]=fx;
else
H=true;
}
int main()
{
int i,x,y,z,o;
while(scanf("%d%d",&N,&M)!=EOF)
{
num=0;
for(i=0;i<=N;i++)
bo[i]=i;
H=false;
memset(head,-1,sizeof(head));
for(i=1;i<=M;i++)
{
scanf("%d%d%d",&x,&y,&z);
o=x;
if(H)
continue;
KL(x,y);
add(x,y,z);
add(y,x,z);
}
if(H)
{
printf("YES\n");
continue;
}
BFS(o);
BFS(cot);
printf("%d\n",ans);
}
return 0;
}