[COGS826][Tyvj Feb11] GF打dota(k短路)

题目描述

传送门

题目大意:给出一个n个点m条边的无向图,当p=0时求最短路,当p=1时求严格次短路。

题解

k短路裸题

代码

#include
#include
#include
#include
#include
#include
using namespace std;
#define N 100005

int n,m,p,s,t,Min;
int tot,point[N],nxt[N],v[N],c[N];
int dis[N];bool vis[N];
struct data
{
    int x,g;
    bool operator < (const data &a) const
    {
        return g+dis[x]>a.g+dis[a.x];
    }
};

void add(int x,int y,int z)
{
    ++tot; nxt[tot]=point[x]; point[x]=tot; v[tot]=y; c[tot]=z;
}
void spfa()
{
    queue <int> q;
    memset(dis,127,sizeof(dis));Min=dis[0];
    dis[t]=0;vis[t]=1;q.push(t);
    while (!q.empty())
    {
        int now=q.front();q.pop();
        vis[now]=0;
        for (int i=point[now];i;i=nxt[i])
            if (dis[v[i]]>dis[now]+c[i])
            {
                dis[v[i]]=dis[now]+c[i];
                if (!vis[v[i]]) vis[v[i]]=1,q.push(v[i]);
            }
    }
}
void Astar()
{
    priority_queue  q;
    q.push((data){s,0});
    while (!q.empty())
    {
        data now=q.top();q.pop();
        if (now.x==t)
        {
            if (now.gif (!p) return;
            else if (now.g>Min) {Min=now.g;return;}
            continue;
        }
        for (int i=point[now.x];i;i=nxt[i])
            q.push((data){v[i],now.g+c[i]});
    }
}
int main()
{
    freopen("dota.in","r",stdin);
    freopen("dota.out","w",stdout);
    scanf("%d%d",&n,&m);
    for (int i=1;i<=m;++i)
    {
        int x,y,z;scanf("%d%d%d",&x,&y,&z);
        add(x,y,z),add(y,x,z);
    }
    scanf("%d",&p);
    s=1,t=n;
    spfa();
    Astar();
    printf("%d\n",Min);
}

你可能感兴趣的:(题解,图论算法)