您的位置:首页 > 其它

题目1545:奇怪的连通图

2014-03-20 16:23 232 查看
题目1545:奇怪的连通图

时间限制:1 秒
内存限制:128 兆
特殊判题:
提交:316
解决:89

题目描述:
已知一个无向带权图,求最小整数k。使仅使用权值小于等于k的边,节点1可以与节点n连通。

输入:
输入包含多组测试用例,每组测试用例的开头为一个整数n(1 <= n <= 10000),m(1 <= m <= 100000),代表该带权图的顶点个数,和边的个数。

接下去m行,描述图上边的信息,包括三个整数,a(1 <= a <= n),b(1 <= b <= n),c(1 <= c <= 1000000),表示连接顶点a和顶点b的无向边,其权值为c。

输出:
输出为一个整数k,若找不到一个整数满足条件,则输出-1。

样例输入:
3 3
1 3 5
1 2 3
2 3 2
3 2
1 2 3
2 3 5
3 1
1 2 3


样例输出:
3
5
-1


思路:稍微改造一下dijkstra,d[i]保存路径中最长道路的最小值,使用优先队列降低计算复杂度O(vlogv)(v是顶点数)

#include <stdio.h>
#include <vector>
#include <queue>
using namespace std;
#define INF 99999999
typedef pair<int, int> p;
int n, m;
struct edge
{
int to, cost;
};
vector<edge> edgeList[10010];
int d[10010];
bool visit[10010];

int max(int a, int b)
{
int res = a > b ? a : b;
return res;
}

void dijkstra(int s)
{
d[s] = 0;
priority_queue <p, vector<p>, greater<p> > que;
que.push(p(0,s));
while(que.size())
{
p curP = que.top();
que.pop();
int Index = curP.second;
if(d[Index] < curP.first)
{
continue;
}
for(int i = 0; i < edgeList[Index].size(); i++)
{
edge tempEdge = edgeList[Index][i];
if(d[tempEdge.to] > max(d[Index], tempEdge.cost))
{
d[tempEdge.to] = max(d[Index], tempEdge.cost);
que.push(p(d[tempEdge.to], tempEdge.to));
}
}
}
}

int main()
{
while(scanf("%d %d", &n, &m) != EOF)
{
for(int i = 1; i <= n; i++)
{
edgeList[i].clear();
d[i] = INF;
visit[i] = false;
}
int a,b,dist;
edge tempS,tempE;
for(int i = 0; i < m; i++)
{
scanf("%d %d %d", &a, &b, &dist);
tempS.to = b;
tempS.cost = dist;
tempE.to = a;
tempE.cost = dist;
edgeList[a].push_back(tempS);
edgeList[b].push_back(tempE);
}
dijkstra(1);
if(d
== INF)
{
printf("-1\n");
}
else
{
printf("%d\n", d
);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: