好题。这题可以有三种解法:1.Dijkstra   2.优先队列   3.并查集

我这里是优先队列的实现,以后有时间再用另两种方法做做。。方法就是每次都选当前节点所连的权值最大的边,然后BFS搜索。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
#include <map>
#include <queue>
#include <functional>
using namespace std;
#define N 100007 struct node
{
int ind,wt;
bool operator < (const node &a)const
{
return wt<a.wt;
}
};
int start,endi,n,m,res;
int way[][],vis[][];
map<string,int> mp;
priority_queue<node> que; void BFS()
{
memset(vis,,sizeof(vis));
int i,maxi = ,id;
node now,next;
for(i=;i<=n;i++)
{
if(way[start][i] > maxi)
{
maxi = way[start][i];
id = i;
}
}
now.ind = id;
now.wt = maxi;
que.push(now);
//printf("%d %d\n",start,endi);
//printf("%d %d\n",now.ind,now.wt);
res = ;
while(!que.empty())
{
now = que.top();
que.pop();
if(now.ind == endi)
{
if(now.wt > res)
res = now.wt;
while(!que.empty())
que.pop();
return;
}
for(i=;i<=n;i++)
{
if(way[now.ind][i] && !vis[now.ind][i])
{
vis[now.ind][i] = vis[i][now.ind] = ;
next.ind = i;
next.wt = min(now.wt,way[now.ind][i]);
que.push(next);
//printf("%d %d\n",next.ind,next.wt);
}
}
}
} int main()
{
int cs = ,i,j,w,num;
string city1,city2;
node ka,kb;
while(scanf("%d%d",&n,&m)!=EOF && (n||m))
{
mp.clear();
num = ;
memset(way,,sizeof(way));
for(i=;i<m;i++)
{
cin>>city1;
cin>>city2;
scanf("%d",&w);
if(!mp[city1])
mp[city1] = num++;
if(!mp[city2])
mp[city2] = num++;
way[mp[city1]][mp[city2]] = w;
way[mp[city2]][mp[city1]] = w;
}
cin>>city1>>city2;
start = mp[city1];
endi = mp[city2];
BFS();
printf("Scenario #%d\n",cs++);
printf("%d tons\n\n",res);
}
return ;
}
04-24 20:24