原题:
The cows have run out of hay, a horrible event that must be remedied immediately. Bessie intends to visit the other farms to survey their hay situation. There are N (2 <= N <= 2,000) farms (numbered 1..N); Bessie starts at Farm 1. She'll traverse some or all of the M (1 <= M <= 10,000) two-way roads whose length does not exceed 1,000,000,000 that connect the farms. Some farms may be multiply connected with different length roads. All farms are connected one way or another to Farm 1.
Bessie is trying to decide how large a waterskin she will need. She knows that she needs one ounce of water for each unit of length of a road. Since she can get more water at each farm, she's only concerned about the length of the longest road. Of course, she plans her route between farms such that she minimizes the amount of water she must carry.
Help Bessie know the largest amount of water she will ever have to carry: what is the length of longest road she'll have to travel between any two farms, presuming she chooses routes that minimize that number? This means, of course, that she might backtrack over a road in order to minimize the length of the longest road she'll have to traverse.
题目很简单,就是求最小生成树中最大的那条边。直接上Prim算法或者Kruskal。
#ifndef HEAD
#include <stdio.h>
#include <vector>
#include <math.h>
#include <string.h>
#include <string>
#include <iostream>
#include <queue>
#include <list>
#include <algorithm>
#include <stack>
#include <map>
using namespace std;
#endif // !HEAD
#ifndef QUADMEMSET
inline void QuadMemSet(void* dst, int iSize, int value)
{
iSize = iSize / 4;
int* newDst = (int*)dst;
#ifdef WIN32
__asm
{
mov edi, dst
mov ecx, iSize
mov eax, value
rep stosd
}
#else
for (int i = 0; i < iSize; i++)
{
newDst[i] = value;
}
#endif
}
#endif
int cost[2001][2001];
int prim(int N)
{
int visited[2001] = { 0 };
int maxcost[2001];
//memset(maxcost, 0, sizeof(maxcost));
memset(visited, 0, sizeof(visited));
QuadMemSet(maxcost, sizeof(maxcost), 1000000001);
for (int i = 1; i <= N; i++)
{
cost[i][i] = 0;
}
maxcost[1] = 0;
int res = 0;
while (true)
{
int v = -1;
for (int i = 1; i <= N; i++)
{
if (!visited[i] && (v == -1 || maxcost[i] < maxcost[v]))
{
v = i;
}
}
if (v < 0 || maxcost[v] > 1000000000)
{
break;
}
visited[v] = 1;
if (res < maxcost[v] )
{
res = maxcost[v];
}
for (int i = 1; i <= N; i++)
{
maxcost[i] = min(maxcost[i], cost[v][i]);
}
}
return res;
}
int main()
{
#ifdef _DEBUG
freopen("d:\\in.txt", "r", stdin);
#endif
int N, M;
QuadMemSet(cost, sizeof(cost), 1000000001);
scanf("%d %d\n", &N, &M);
for (int i = 0; i < M; i++)
{
int a, b, c;
scanf("%d %d %d\n", &a, &b, &c);
cost[a][b] = min(c, cost[a][b]);
cost[b][a] = min(c, cost[b][a]);
}
printf("%d\n", prim(N));
return 0;
}