码迷,mamicode.com
首页 > 其他好文 > 详细

POJ 1122 FDNY to the Rescue!

时间:2014-07-02 09:47:43      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:最短路   spfa   

给出某些交叉点的距离,-1 表示无法到达。

然后给出火灾发生点  和 附近的消防局位置。

排列消防局 的 时间 与路径。


反向建图,以火灾出发点为起点做一次SPFA。

#include<cstdio>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<queue>
#include<map>
#include<stack>
#include<iostream>
#include<list>
#include<set>
#include<cmath>
#define INF 0x7fffffff
#define eps 1e-6
using namespace std;
int n;
struct lx
{
    int v,t;
};
vector<lx>g[21];
bool vis[21];
int path[21];
int dis[21];
void SPFA(int start)
{
    for(int i=1;i<=n;i++)
        dis[i]=INF,vis[i]=0,path[i]=0;
    queue<int>q;
    vis[start]=1,dis[start]=0;
    q.push(start);
    while(!q.empty())
    {
        int u=q.front();q.pop();
        vis[u]=0;
        for(int j=0;j<g[u].size();j++)
        {
            int v=g[u][j].v;
            int t=g[u][j].t;
            if(dis[v]>dis[u]+t)
            {
                dis[v]=dis[u]+t;
                path[v]=u;// 记录路径
                if(!vis[v])
                {
                    vis[v]=1;
                    q.push(v);
                }
            }
        }
    }
}
struct node
{
    int Org,time;
}l[21];
bool cmp(node a,node b)
{
    return a.time<b.time;
}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                int t;
                scanf("%d",&t);
                if(i==j||t==-1)continue;
                lx now;
                now.v=i,now.t=t;
                g[j].push_back(now);
            }
        }
        int start,endcot=0;
        int thend[21];
        scanf("%d",&start);
        getchar();
        char str[101];
        gets(str);
        int i=0;
        int c=0;
        while(str[i]==' ')i++;
        for(i=0;i<=strlen(str);i++)
        {
            while(str[i]>='0'&&str[i]<='9')c=c*10+str[i]-'0',i++;
            if(c!=0)
                thend[endcot++]=c,c=0;
        }
        SPFA(start);
        for( i=0;i<endcot;i++)
        l[i].Org=thend[i],l[i].time=dis[thend[i]];
        sort(l,l+endcot,cmp);
        puts("Org	Dest	Time	Path");
        for( i=0;i<endcot;i++)
        {
            int v=l[i].Org;
            printf("%d	%d	%d",v,start,dis[v]);
            int tmp=v;
            while(path[tmp]!=0)
                printf("	%d",tmp),tmp=path[tmp];
            printf("	%d\n",start);

        }
    }
}


POJ 1122 FDNY to the Rescue!,布布扣,bubuko.com

POJ 1122 FDNY to the Rescue!

标签:最短路   spfa   

原文地址:http://blog.csdn.net/dongshimou/article/details/36188417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!