BZOJ_1614_ [Usaco2007_Jan]_Telephone_Lines_架设电话线_(二分+最短路_Dijkstra/Spfa)

时间:2021-11-17 14:43:56

描述


http://www.lydsy.com/JudgeOnline/problem.php?id=1614

分析


类似POJ_3662_Telephone_Lines_(二分+最短路)

Dijkstra:

 #include <bits/stdc++.h>
using namespace std; const int maxn=+,maxm=+,INF=<<;
int n,m,k,ect;
int hd[maxn],f[maxm],d[maxn];
bool vis[maxn];
struct edge{
int to,w,next;
edge(int to=,int w=,int next=):to(to),w(w),next(next){}
bool operator < (const edge &a) const { return w>a.w; }
}g[maxm<<];
inline int read(int &x){ x=;int k=;char c;for(c=getchar();c<''||c>'';c=getchar())if(c=='-')k=-;for(;c>=''&&c<='';c=getchar())x=x*+c-'';return x*=k; }
inline void add_edge(int u,int v,int w){
g[++ect]=edge(v,w,hd[u]); hd[u]=ect;
g[++ect]=edge(u,w,hd[v]); hd[v]=ect;
}
inline bool C(int x){
for(int i=;i<=n;i++) d[i]=INF, vis[i]=false;
d[]=;
priority_queue <edge> q;
q.push(edge(,,));
while(!q.empty()){
int u=q.top().to; q.pop();
if(vis[u]) continue;
vis[u]=true;
for(int i=hd[u];i;i=g[i].next){
int v=g[i].to,duv=g[i].w>x?:;
if(d[v]>d[u]+duv){
d[v]=d[u]+duv;
q.push(edge(v,d[v],));
}
}
}
return d[n]<=k;
}
inline int bsearch(int l,int r){
if(!C(f[r])) return-;
while(l<r){
int mid=l+(r-l)/;
if(C(f[mid])) r=mid;
else l=mid+;
}
return f[l];
}
int main(){
read(n); read(m); read(k);
for(int i=,u,v,w;i<=m;i++){
read(u); read(v); read(w);
add_edge(u,v,w);
f[i]=w;
}
sort(f+,f++m);
printf("%d\n",bsearch(,m));
return ;
}

Spfa:

 #include <bits/stdc++.h>
using namespace std; const int maxn=+,maxm=+,INF=<<;
int n,m,k,ect;
int hd[maxn],q[maxn],f[maxm],d[maxn];
bool vis[maxn];
struct edge{
int to,w,next;
edge(int to=,int w=,int next=):to(to),w(w),next(next){}
}g[maxm<<];
inline int read(int &x){ x=;int k=;char c;for(c=getchar();c<''||c>'';c=getchar())if(c=='-')k=-;for(;c>=''&&c<='';c=getchar())x=x*+c-'';return x*=k; }
inline void add_edge(int u,int v,int w){
g[++ect]=edge(v,w,hd[u]); hd[u]=ect;
g[++ect]=edge(u,w,hd[v]); hd[v]=ect;
}
inline bool C(int x){
for(int i=;i<=n;i++) d[i]=INF, vis[i]=false;
d[]=,vis[]=true;
int l=,r=;
q[r++]=;
while(l!=r){
int u=q[l++]; if(l==maxn-) l=;
vis[u]=false;
for(int i=hd[u];i;i=g[i].next){
int v=g[i].to,duv=g[i].w>x?:;
if(d[v]>d[u]+duv){
d[v]=d[u]+duv;
if(!vis[v]){
q[r++]=v; if(r==maxn-) r=;
vis[v]=true;
}
}
}
}
return d[n]<=k;
}
inline int bsearch(int l,int r){
if(!C(f[r])) return-;
while(l<r){
int mid=l+(r-l)/;
if(C(f[mid])) r=mid;
else l=mid+;
}
return f[l];
}
int main(){
read(n); read(m); read(k);
for(int i=,u,v,w;i<=m;i++){
read(u); read(v); read(w);
add_edge(u,v,w);
f[i]=w;
}
sort(f+,f++m);
printf("%d\n",bsearch(,m));
return ;
}