題目鏈接:https://www.luogu.com.cn/problem/P2330
題目第一條件要讓所有交叉路口連接起來,這就是要讓圖上所有點連通。第二個條件要用最少道路,顯而易見是找生成樹。第三個條件要使分值最大的道路分值儘量小,就是要找最小生成樹。這裏我用的是kruskal算法,最後一條被添加的邊的長度就是生成樹中分值最大的邊。
代碼如下
#include <bits/stdc++.h>
using namespace std;
const int maxn=305;
const int inf=0xfffffff;
struct node
{
int from;
int to;
int cost;
friend bool operator < (node a,node b)
{
return a.cost > b.cost;
}
}p;
int fa[maxn];
int n,m;
priority_queue<node>q;//優先隊列
int find(int x)
{
if(x==fa[x])
return x;
return fa[x]=find(fa[x]);
}
int kruskal()//求生成樹
{
int ans=0;
while(!q.empty())
{
node temp=q.top();
q.pop();
int x=temp.from,y=temp.to,c=temp.cost;
int xx=find(x),yy=find(y);
//cout<<x<<" "<<y<<endl;
//cout<<fa[x]<<" "<<fa[y]<<endl;
if(xx!=yy)
ans=c,fa[xx]=yy;//加入生成樹,更新最大值
//cout<<ans<<endl;
}
return ans;
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++)
fa[i]=i;//初始祖先節點是自己
for(int i=1;i<=m;i++)
{
scanf("%d %d %d",&p.from,&p.to,&p.cost);
q.push(p);
}
printf("%d %d\n",n-1,kruskal());
return 0;
}