POJ Remmarguts' Date

题目链接->

POJ Remmarguts' Date_第1张图片

POJ Remmarguts' Date_第2张图片

题解:

次短路模板。

代码:

#include
#include
using namespace std;
#define inf 1e9
#define N 100005
#define S1 dis[x]+e[i].v
#define S2 sdis[x]+e[i].v
using namespace std;
struct node {
    int to,next,v;
} e[N<<1];  
int head[N],cnt;
void insert(int x, int y, int v) {
    e[++cnt].to=y;
    e[cnt].next=head[x];
    e[cnt].v=v;
    head[x]=cnt;
}
int n,m,dis[N],sdis[N],q[N<<2];
bool inq[N];
void SPFA() {
    for(int i=1; i<=n; i++)dis[i]=sdis[i]=inf;
    dis[1]=0;
    q[0]=inq[1]=1;
    int l=0,r=1,t;
    while (l<r) {
        int x=q[l++]; 
        for (int i=head[x]; i; i=e[i].next) {
            t=e[i].to; 
            if (dis[t]>S1) {
                sdis[t]=dis[t];
                dis[t]=S1;
                if (!inq[t])inq[t]=1,q[r++]=t;
            }
            if (dis[t]S1) {
                sdis[t]=S1;
                if (!inq[t])inq[t]=1,q[r++]=t;
            }
            if (sdis[t]>S2) {
                sdis[t]=S2;
                if (!inq[t])inq[t]=1,q[r++]=t;
            }
        }
        inq[x]=0;
    }
}
int main() {
    cin>>n>>m;
    for (int i=1,x,y,v; i<=m; i++) {
        cin>>x>>y>>v;   
        insert(x,y,v);
        insert(y,x,v);
    }
    SPFA(); 
    cout<<sdis[n];
    return 0;
} 
spfa
#include 
#include 
#include 
#include 
#include 
const int MAX = 999999;
const int INF = 0x7fffffff;
using namespace std;
struct Edge {
    int num,len;
    bool operator <(const Edge &a)const {
        return a.len < len;
    }
}temp;
int u[MAX],v[MAX],w[MAX],dis[MAX],second[MAX],first[MAX / 4],next[MAX],n,r;
void dijkstra() {
    priority_queue que;
    dis[0] = 0;
    second[0] = INF;
    for(int i = 0; i < n; i++) dis[i] = second[i] = INF;
    temp.len = temp.num = 0;
    que.push(temp);
    while(!que.empty()) {
        Edge head = que.top();
        que.pop();
        if(head.len > second[head.num]) continue;
        int k = first[head.num];
        while(k != -1) {
            int d = head.len + w[k];
            if(dis[v[k]] > d) {
                swap(dis[v[k]], d);
                temp.len = dis[v[k]];
                temp.num = v[k];
                que.push(temp);
            }
            if(dis[v[k]] < d && second[v[k]] > d) {
                second[v[k]] = d;
                temp.len = second[v[k]];
                temp.num = v[k];
                que.push(temp);
            }
            k = next[k];
        }
    }
}
int main() {
    scanf("%d%d",&n,&r);
    memset(first, -1, sizeof(first));
    for(int i = 0; i < r; i++) { 
        scanf("%d%d%d",&u[i],&v[i],&w[i]);
        u[i]--,v[i]--,next[i] = first[u[i]],first[u[i]] = i,u[i + r] = v[i];
        v[i + r] = u[i],w[i + r] = w[i],next[i + r] = first[u[i + r]],first[u[i + r]] = i + r;
    }
    dijkstra(); 
    printf("%d",second[n-1]);
    return 0;
}
dijkstra

一世安宁

转载于:https://www.cnblogs.com/GTBA/p/9805729.html

你可能感兴趣的:(数据结构与算法)