hdu2066最短路径spfa算法对每个点分别判断0ms过

#include<iostream>

#include<vector>

#include<queue>



using namespace std;

const int MAXN=1005;

const int MAX=999999999;

struct edge

{

    int from,to,cost;

};

vector<edge>v[MAXN];

int dist[MAXN];

bool in_queue[MAXN];

void init()

{

    int i=0;

    for(i=0;i<=MAXN-1;i++)

    {

        v[i].clear();

    }

    memset(in_queue,0,sizeof(in_queue));

}

void spfa(int p)

{

    queue<int>q;

    int i=0;

    for(i=0;i<=MAXN-1;i++)

    {

        dist[i]=MAX;

    }

    while(!q.empty())

    {

        q.pop();

    }

    dist[p]=0;

    q.push(p);

    in_queue[p]=1;

    while(!q.empty())

    {

        int cur=q.front();

        int i=0;

        q.pop();

        in_queue[cur]=0;

        for(i=0;i<=int(v[cur].size())-1;i++)

        {

            int cost=v[cur][i].cost+dist[cur];

            int to=v[cur][i].to;

            if(cost<dist[to])

            {

                dist[to]=cost;

                if(!in_queue[to])

                {

                    q.push(to);

                    in_queue[to]=1;

                }

            }

        }

    }

}

int main()

{

    int T,S,D;

    while(cin>>T>>S>>D)

    {

        init();

        while(T--)

        {

            int from,to,cost;

            cin>>from>>to>>cost;

            edge e={from,to,cost};

            v[e.from].push_back(e);

            swap(e.from,e.to);

            v[e.from].push_back(e);

        }

        int i,j;

        int f[MAXN];

        int t[MAXN];

        int min=-1;

        for(i=0;i<=S-1;i++)

        {

            cin>>f[i];

        }

        for(i=0;i<=D-1;i++)

        {

            cin>>t[i];

        }

        for(i=0;i<=S-1;i++)

        {

            memset(in_queue,0,sizeof(in_queue));

            spfa(f[i]);

            for(j=0;j<=D-1;j++)

            {

               // cout<<dist[t[j]]<<endl;

                if(dist[t[j]]<min||min==-1)

                {

                    min=dist[t[j]];

                }

            }

        }

        cout<<min<<endl;

    }

    return 0;

}

  

你可能感兴趣的:(最短路径)