您的位置:首页 > 其它

bzoj 3575: [Hnoi2014]道路堵塞 spfa

2016-04-20 08:46 429 查看
这道题目是玄学时间复杂度。。。(一定是窝太弱不会证明)。

显然,如果去掉某一条最短路上的边,剩下的最短路径为S->沿着最短路径->u->其他边->v->沿着最短路径->T。那么我们可以求出每一个u,v的最短路。具体可以选择一个u,然后不走从u出发的最短路的那条边,看到达的v能否更新答案。实际上就是加入一个堆。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define N 100005
#define M 300005
using namespace std;

int n,m,cnt,tot,a
,b
,pos
,fst
,pnt[N<<1],nxt[N<<1],len[N<<1],f
,g
;
int h[M+5],d
,val
,tp,stk
; bool bo
,mrk
;
struct node{ int x,y; }; bool operator <(node u,node v){ return u.y>v.y; }
priority_queue<node> q;
int read(){
int x=0; char ch=getchar();
while (ch<'0' || ch>'9') ch=getchar();
while (ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); }
return x;
}
void add(int x,int y,int z){
pnt[++tot]=y; len[tot]=z; nxt[tot]=fst[x]; fst[x]=tot;
}
void spfa(int sta,int w,int u,int v){
memset(bo,1,sizeof(bo)); memset(mrk,0,sizeof(mrk));
d[sta]=w; h[1]=sta;
int head=0,tail=1;
while (head!=tail){
head=head%M+1; int x=h[head],p; bo[x]=1;
for (p=fst[x]; p; p=nxt[p]) if (p!=u){
int y=pnt[p];
if (pos[y]>v)
if (!mrk[y]){
mrk[y]=1; stk[++tp]=y;
val[y]=d[x]+len[p]+g[pos[y]];
} else val[y]=min(val[y],d[x]+len[p]+g[pos[y]]);
else
if (d[x]+len[p]<d[y]){
d[y]=d[x]+len[p];
if (bo[y]){
bo[y]=0; tail=tail%M+1;
h[tail]=y;
}
}
}
}
for (; tp; tp--) q.push((node){pos[stk[tp]],val[stk[tp]]});
}
int main(){
n=read(); m=read(); cnt=read(); int i,x,y,z;
for (i=1; i<=m; i++){
x=read(); y=read(); z=read();
add(x,y,z);
}
b[1]=pos[1]=1;
for (i=1; i<=cnt; i++){
a[i]=read();
b[i+1]=pnt[a[i]]; pos[b[i+1]]=i+1;
}
for (i=1; i<=cnt; i++) f[i+1]=f[i]+len[a[i]];
for (i=cnt; i; i--) g[i]=g[i+1]+len[a[i]];
memset(d,0x3f,sizeof(d)); d[1]=0;
for (i=1; i<=cnt; i++){
spfa(b[i],f[i],a[i],i);
while (!q.empty() && q.top().x<=i) q.pop();
printf("%d\n",q.empty()?-1:q.top().y);
}
return 0;
}


by lych
2016.4.20
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: