这其实就是一个最小生成树的问题,用prim算法直接做就好了
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
typedef pair<int, int> P;
vector<P> edges[2007];
int N, M, mincost[2007], inf = 0x3f3f3f3f;
bool T[2007];
void input()
{
int from = 0, to = 0, len = 0;
for (int i = 1; i <= M; i++)
{
scanf("%d%d%d", &from, &to, &len);
edges[from].push_back(P(len, to));
edges[to].push_back(P(len, from));
}
}
void prim(int s)
{
for (int i = 1; i <= N; i++)
{
mincost[i] = inf;
}
mincost[s] = 0;
priority_queue<P, vector<P>, greater<P>> que;
que.push(P(0, s));
while (!que.empty())
{
P current = que.top();
que.pop();
if (T[current.second] || current.first > mincost[current.second])
{
continue;
}
T[current.second] = true;
for (int i = 0; i < edges[current.second].size(); i++)
{
P toEdge = edges[current.second][i];
if (!T[toEdge.second] && toEdge.first < mincost[toEdge.second])
{
mincost[toEdge.second] = toEdge.first;
que.push(P(toEdge.first, toEdge.second));
}
}
}
}
int findAns()
{
int ans = mincost[1];
for (int i = 2; i <= N; i++)
{
if (mincost[i] > ans)
{
ans = mincost[i];
}
}
return ans;
}
int main()
{
scanf("%d%d", &N, &M);
input();
prim(1);
printf("%d\n", findAns());
return 0;
}