Telephone Lines
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3468 | Accepted: 1245 |
Description
Farmer John wants to set up a telephone line at his farm. Unfortunately, the phone company is uncooperative, so he needs to pay for some of the cables required to connect his farm to the phone system.
There are N (1 ≤ N ≤ 1,000) forlorn telephone poles conveniently numbered 1..N that are scattered around Farmer John's property; no cables connect any them. A total ofP (1 ≤ P ≤ 10,000) pairs of poles can be connected by a cable; the rest are too far apart.
The i-th cable can connect the two distinct poles Ai andBi, with length Li (1 ≤ Li ≤ 1,000,000) units if used. The input data set never names any {Ai,Bi} pair more than once. Pole 1 is already connected to the phone system, and pole N is at the farm. Poles 1 andN need to be connected by a path of cables; the rest of the poles might be used or might not be used.
As it turns out, the phone company is willing to provide Farmer John with K (0 ≤ K < N) lengths of cable for free. Beyond that he will have to pay a price equal to the length of the longest remaining cable he requires (each pair of poles is connected with a separate cable), or 0 if he does not need any additional cables.
Determine the minimum amount that Farmer John must pay.
Input
* Line 1: Three space-separated integers: N, P, and K
* Lines 2..P+1: Line i+1 contains the three space-separated integers:Ai, Bi, and Li
Output
* Line 1: A single integer, the minimum amount Farmer John can pay. If it is impossible to connect the farm to the phone company, print -1.
Sample Input
5 7 1 1 2 5 3 1 4 2 4 8 3 2 3 5 2 9 3 4 7 4 5 6
Sample Output
4
Source
#include <iostream>
#include <algorithm>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <queue>
#include <utility>
using namespace std;
const int INF = 0x3fffffff;
int visited[1005];
int dis[1005];
int ans[10005];
int n, p, k;
vector<pair<int, int> > g[1005];
int spfa(int now_dis) {
for (int i = 1; i <= n; ++i) {
dis[i] = INF;
}
queue<int> que;
int cur = 1;
que.push(cur);
visited[cur] = 1;
dis[cur] = 0;
while (!que.empty()) {
cur = que.front();
que.pop();
visited[cur] = 0;
for (int i = 0; i < g[cur].size(); ++i) {
int v = g[cur][i].first;
int w = g[cur][i].second;
if (w > now_dis)
w = 1;
else
w = 0;
if (w + dis[cur] < dis[v]) {
dis[v] = w + dis[cur];
if (!visited[v]) {
que.push(v);
visited[v] = 1;
}
}
}
}
if (dis[n] <= k)
return 1;
else
return 0;
}
int main() {
//freopen("in.txt", "r", stdin);
while (cin >> n >> p >> k) {
for (int i = 1; i <= n; ++i) {
g[i].clear();
}
int m = -1;
for (int i = 1; i <= p; ++i) {
int a, b, c;
cin >> a >> b >> c;
g[a].push_back(make_pair(b, c));
g[b].push_back(make_pair(a, c));
m = max(m, c);
}
int left = 0, right = m + 1;
while (left < right) {
int mid = (left + right) >> 1;
if (spfa(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
if (dis[n] == INF)
cout << -1 << endl;
else
cout << left << endl;
}
}