$Kruskal$算法(334ms)$O(mlogm)$
核心:按边长从小到大枚举边,第一次使得1和n连通的边的长度即为答案
#include <algorithm>
#include <cstring>
#include <iostream>
using namespace std;
const int N = 100010, M = 400010;
struct Edge
{
int a, b, c;
bool operator<(const Edge &t) const
{
return c < t.c;
}
} e[M];
int n, m;
int p[N];
int find(int x)
{
if (p[x] != x)
p[x] = find(p[x]);
return p[x];
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 0; i < m; i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
e[i] = {a, b, c};
}
sort(e, e + m);
for (int i = 1; i <= n; i++)
p[i] = i;
for (int i = 0; i < m; i++)
{
int a = e[i].a, b = e[i].b;
a = find(a), b = find(b);
if (a != b)
{
p[a] = b;
if (find(1) == find(n))
{
printf("%d", e[i].c);
break;
}
}
}
return 0;
}
堆优化$dijkstra$算法的变种用法(834ms)$O(mlogn)$
核心:$dist[j] = max(dist[t.y], w[i])$;
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
#define x first
#define y second
using namespace std;
const int N = 100010, M = 400010;
typedef pair<int, int> PII;
int n, m;
int h[N], e[M], ne[M], w[M], idx;
int dist[N];
bool st[N];
void add(int a,int b,int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int dijkstra()
{
memset(dist, 0x3f, sizeof dist);
priority_queue<PII, vector<PII>, greater<PII>> q;
q.push({0, 1});
dist[1] = 0;
while (q.size())
{
auto t = q.top();
q.pop();
if(st[t.y])
continue;
st[t.y] = true;
for (int i = h[t.y]; ~i;i=ne[i])
{
int j = e[i];
if(dist[j]>max(dist[t.y],w[i]))
{
dist[j] = max(dist[t.y], w[i]);
if(!st[j])
q.push({dist[j], j});
}
}
}
return dist[n];
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
for (int i = 0; i < m;i++)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c), add(b, a, c);
}
cout << dijkstra() << endl;
return 0;
}