为什么我写的二分+SPFA会超时,只过了两个点。求助大犇

P1462 通往奥格瑞玛的道路

duzhenbang @ 2016-11-15 16:03:15

#include<cstring>
#include<cstdio>
#include<iostream>
#include<queue>
using namespace std;
struct node {
    int v,w,next;
} edge[50001];
queue<long long>q;
int tot=0,n,m;
long long b,maxa=0,mid;
long long fi[10001],dist[10001];
int head[50001];
bool visit[10001];
bool panduan=true;
int addedge(int vi,int ui,int wi) {
    edge[tot].v=ui;
    edge[tot].w=wi;
    edge[tot].next=head[vi];
    head[vi]= tot++;
}
bool spfa(long long mid) {
    while(!q.empty())q.pop();
    memset(visit,true,sizeof(visit));
    memset(dist,0x7f,sizeof(dist));
    dist[1]=0;
    visit[1]=false;
    q.push(1);
    for(int i=1; i<=n; ++i)
        if(fi[i]>mid)visit[i]=false;
    if(fi[1]>mid||fi[n]>mid)return 0;
    while(!q.empty()) {
        long long x=q.front();
        q.pop();
        visit[x]=true;
        for(long long i=head[x]; i!=0; i=edge[i].next) {
            long long u=edge[i].v;
            if(dist[u]>dist[x]+edge[i].w) {
                dist[u]=dist[x]+edge[i].w;
                if(visit[u]==true) {
                    visit[u]=false;
                    q.push(u);

                }
            }
        }
    }
    if(dist[n]>b)return 0;
    return 1;

}

int main() {
    cin>>n>>m>>b;
    for(int i=1; i<=n; ++i) {
        cin>>fi[i];
        maxa=max(maxa,fi[i]);
    }
    for(int i=1; i<=m; ++i) {
        long long x,y,z;
        cin>>x>>y>>z;
        addedge(x,y,z);
        addedge(y,x,z);
    }
    long long l,r;
    l=1;
    r=maxa;
    while(l!=r) {
        mid=(l+r)/2;
        if(spfa(mid)==0)l=mid+1;
        else r=mid;

    }
    if(spfa(l)==0)cout<<"AFK";
    else cout<<l;

}

|