多源点对单终点问题

https://vjudge.net/problem/HDU-2680

思路:单边,将终点看做起点,反向建立图,否则超时

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

const int maxn = 40000 + 20;
const int INF = 1<<20;
struct Node
{
    int from,to,cost;
}es[maxn];
int d[maxn];
int v,e;

void BellMan(int End)
{
    for(int k = 1;k <= v;k++)
    {
        d[k] = INF;
    }
    d[End] = 0;
    while(1)
    {
        int update = 0;
        for(int j  = e;j < 2*e;j++)//只遍历反向边
        {
            Node E = es[j];
            if(d[E.from]!=INF && d[E.to] > d[E.from] + E.cost)
            {
                d[E.to] = d[E.from] + E.cost;
                update = 1;
            }
        }
        if(!update) break;
    }
}

int main()
{
    int End;
    while(~scanf("%d%d%d",&v,&e,&End))
    {
        for(int  i = 0;i < e;i++)
        {
            scanf("%d%d%d",&es[i].from,&es[i].to,&es[i].cost);
            es[i+e].from = es[i].to;//反向建图
            es[i+e].to = es[i].from;
            es[i+e].cost = es[i].cost;
        }
        int w;
        scanf("%d",&w);
        int Begin[maxn];
        for(int j = 0;j < w;j++)
        {
            scanf("%d",&Begin[j]);
        }
        BellMan(End);
        int minn = INF;
        for(int i = 0;i < w;i++)
        {
            if(minn>d[Begin[i]])
                minn = d[Begin[i]];
        }

        if(minn == INF)
            printf("-1 ");
        else
            printf("%d ",minn);
    }
    return 0;
}

原文地址:https://www.cnblogs.com/unknownname/p/7754359.html