Gym 101666D(最短路)

传送门

题面:PDF

题意:

    给你n个点,m条路,对于每个点而言,每个点到的1号点最短路都不能行走,问你在这样的情况下从0号点走到1号点的最短路径。

题目分析:

    我们考虑跑两边dijk。在第一次dijk中,在每次松弛操作的过程中用pre数组记录该去边to的父亲结点x,而在第二次dijk的过程中,倘若发现当前要遍历到的点x的后继to正好是自己的父亲,则证明这两个点必定在某条最短路上,则不遍历它们。之后再记录一下此时的路径即可。

代码:

#include <bits/stdc++.h>
#define maxn 100005
#define maxm 1000005
using namespace std;
typedef long long ll;
const ll INF=0x3f3f3f3f3f3f3f3f;
struct edge{
    int to,next,cost;
}q[maxm<<1];
int head[maxn],cnt=0;
int pre[maxn],fpre[maxn];
void init(){
    memset(head,-1,sizeof(head));
    memset(pre,-1,sizeof(pre));
    memset(fpre,-1,sizeof(fpre));
    cnt=0;
}
void add_edge(int from,int to,int cost){
    q[cnt].cost=cost;
    q[cnt].to=to;
    q[cnt].next=head[from];
    head[from]=cnt++;
}
ll d[maxn];
vector<int>vec;
typedef pair<ll,int>PLL;
void dijk(int x){
    memset(d,INF,sizeof(d));
    d[x]=0;
    priority_queue<PLL,vector<PLL>,greater<PLL> >que;
    que.push(make_pair(d[x],x));
    while(!que.empty()){
        PLL p=que.top();
        que.pop();
        x=p.second;
        if(d[x]<p.first) continue;
        for(int i=head[x];i!=-1;i=q[i].next){
            int to=q[i].to;
            if(d[to]>d[x]+q[i].cost){
                d[to]=d[x]+q[i].cost;
                pre[to]=x;//记录父亲
                que.push(make_pair(d[to],to));
            }
        }
    }
}
void bfs(int x,ll &res){
    memset(d,INF,sizeof(d));
    d[x]=0;
    priority_queue<PLL,vector<PLL>,greater<PLL> >que;
    que.push(make_pair(d[0],x));
    while(!que.empty()){
        PLL p=que.top();
        que.pop();
        x=p.second;
        if(d[x]<p.first) continue;
        for(int i=head[x];i!=-1;i=q[i].next){
            int to=q[i].to;
            if(pre[x]==to) continue;倘若x的父亲是to,则不遍历to
            if(d[to]>d[x]+q[i].cost){
                d[to]=d[x]+q[i].cost;
                fpre[to]=x;//再次记录此时的路径
                que.push(make_pair(d[to],to));
            }
        }
    }
    res=d[1];
}
int main()
{
    int n,m;
    init();
    scanf("%d%d",&n,&m);
    for(int i=1;i<=m;i++){
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        add_edge(a,b,c);
        add_edge(b,a,c);
    }
    ll res=0;
    dijk(1);
    bfs(0,res);
    if(res>=INF){
         puts("impossible");
         return 0;
    }
    int cur=1;
    while(fpre[cur]!=-1){
        vec.push_back(cur);
        cur=fpre[cur];
    }
    vec.push_back(cur);
    int sz=vec.size();
    printf("%d ",sz);
    for(int i=sz-1;i>=0;i--){
        if(i==sz-1) printf("%d",vec[i]);
        else printf(" %d",vec[i]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Chen-Jr/p/11007201.html