POJ 3662 Telephone Lines

这道题有两种解法,第二种是以后会写的动态规划,还有就是二分加最短路,这是最小化图中第k大的值,不难想到二分花费,对于大于此花费边权为1,其他为0,之后dijkstra最短路是否小于等于k,来进行判断,其实只有0和1的边也可以通过双端队列bfs来处理

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
const int maxn=20005;
typedef pair<int,int> p;
int n,m,k;
int vis[maxn],dis[maxn];
int num=0,head[maxn];
inline int read()
{
	int x=0,t=1;char ch=getchar();
	while(ch>'9'||ch<'0'){if(ch=='-')t=-1;ch=getchar();}
	while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*t;
}
struct node{
	int v,w,nex;
}e[maxn];
void add(int u,int v,int w)
{
	e[++num].v=v;
	e[num].w=w;
	e[num].nex=head[u];
	head[u]=num;
}
int check(int x)
{
	priority_queue<p,vector<p>,greater<p> >q;
	memset(vis,0,sizeof(vis));
	memset(dis,0x3f,sizeof(dis));
	dis[1]=0;
	q.push(make_pair(0,1));
	while(!q.empty())
	{
		int u=q.top().second;
		q.pop();
		if(vis[u]) continue;
		vis[u]=1;
		for(int i=head[u];i;i=e[i].nex)
		{
			int v=e[i].v;
			if(dis[v]>dis[u]+(e[i].w-x>0?1:0))
			{
				dis[v]=dis[u]+(e[i].w-x>0?1:0);
				q.push(make_pair(dis[v],v));
			}
		}
	}
	return dis[n]<=k;
}
int main()
{
	n=read(),m=read(),k=read();
	for(int i=1;i<=m;i++)
	{
		int x,y,z;
		x=read(),y=read(),z=read();
		add(x,y,z);
		add(y,x,z);
	}
	int l=0,r=1000002;
	while(l<r)
	{
		int mid=(l+r)>>1;
		if(check(mid)) r=mid;
		else l=mid+1;
	}
	if(l>1000000) printf("-1\n");
	else printf("%d\n",l);
	return 0;
}