題目鏈接 點擊打開鏈接
題目的大意是,有一個圖,要從編號爲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;
}
}