DIjkstra(链式前向星建图)

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define INF 0x3f3f3f
int gcd(int a, int b) {return b==0 ? a:gcd(b,a%b);}
const int N = 1010;
int n, m;
int S, E;
int cnt, flag;
int head[N];
int vis[N];
int dis[N];
struct ed
{
    int to, ne, w;
}e[N*100];

struct node
{
    int x, dis;
    bool operator < (const node &a) const
    {
        return a.dis < dis;
    }
};

void add(int u, int v, int w)
{
    e[cnt].to = v;
    e[cnt].ne = head[u];
    e[cnt].w = w;
    head[u] = cnt++;
    e[cnt].to = u;
    e[cnt].ne = head[v];
    e[cnt].w = w;
    head[v] = cnt++;
}

void Dij()
{
    dis[S] = 0;
    priority_queue<node>q;
    q.push((node){S,0});
    while(!q.empty())
    {
        node p = q.top(); q.pop();
        if(p.x==E){
            flag = 1;
        }
        int x = p.x;
        if(vis[x]) continue;
        vis[x] = 1;
        for(int i = head[x]; i+1; i = e[i].ne)
        {
            int y = e[i].to;
            if(!vis[y]&&dis[y]>dis[x]+e[i].w){
                dis[y] = dis[x]+e[i].w;
                q.push((node){y,dis[y]});
            }
        }
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        cnt = flag = 0;
        memset(vis,0,sizeof(vis));
        memset(head,-1,sizeof(head));
        memset(dis,INF,sizeof(dis));
        scanf("%d %d", &n, &m);
        int u, v, w;
        while(m--)
        {
            scanf("%d %d %d", &u, &v, &w);
            add(u,v,w);
        }
        scanf("%d %d", &S, &E);
        Dij();
        if(flag) printf("%d\n", dis[E]);
        else printf("-1\n");
    }
    return 0;
}

你可能感兴趣的:(模板)