题目链接 点击打开链接
题目的大意是,有一个图,要从编号为1的点走到编号为n的点,每条路都有一个承重量,那么从1到n能够运输的重量就取决于这条路上最小的那条边的承重量。要求的是走一次能够运输的最大的重量(即所有可以走的路经中,使得最小承重梁的那条边最大)。
思路是Kruscal算法,将边从大到小将边加进去(这个和Kruscal算法流程一样),如果加一条边就会减少一个联通分量,如果加了一条边之后1和n在同一个联通分量中了,那么这条加的边就是答案,因为之前的边都比他大。
代码如下:
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
struct Edge
{
int start, end, weight;
} edge[1999999];
bool cmp(const Edge &a, const Edge &b)
{
return a.weight > b.weight;
}
int pre[1009];
int find(int x)
{
int y = x;
while (pre[y] != -1) y = pre[y];
int z = x, tmp;
while (pre[z] != -1) tmp = pre[z], pre[z] = y, z = tmp;
return y;
}
int main()
{
int T;
cin >> T;
for (int cas=1; cas<=T; cas++)
{
int n, m;
cin >> n >> m;
for (int i=0; i<m; i++)
{
cin >> edge[i].start >> edge[i].end >> edge[i].weight;
}
sort(edge, edge + m, cmp);
int ans = 0;
memset(pre, -1, sizeof(pre));
for (int i=0; i<m; i++)
{
int xx = find(edge[i].start);
int yy = find(edge[i].end);
if (xx != yy)
{
pre[xx] = yy;
if (find(1) == find(n))
{
ans = edge[i].weight;
break;
}
}
}
cout << "Scenario #" << cas << ":" << endl << ans << endl << endl;
}
}