SSL 2643_城市规划_spfa+dfs

发布于 2019-05-22  860 次阅读


题目描述

东莞九月份要禁摩托车了,但政府也要考虑市民出行的交通问题,为此,政府组织交通局等部门对市内各镇区的交通问题进行调研,小李是负责镇区间距离统计的,他得到了一张全市各镇区的交通路线图,从图中可知镇与镇之间有没有直接到达的路线,如果有,也已知距离长度,当然,由于某些镇的交通比较落后,可能与其他镇都没有路线到达。现在政府要小李向上级汇报任意指定的两个镇区之间的最长距离和最短距离。


思路

用spfa很容易求出最短路
而最长路就要跑一般dfs了,每个点只可以走一遍


#include <stdio.h>
#include <algorithm>
#include <algorithm>
#include <queue>
#include <string>
#include <cstring>
using namespace std;
#define fill(x,y) memset(x,y,sizeof(x))
#define maxn 101
#define INF 0x7f7f7f7f
int n,a,b;
struct edge
{
    int to,w,next;
}e[maxn];
int ls[maxn],exits[maxn],state[maxn];
int spfa()
{
    queue<int> t;
    t.push(a);
    fill(state,INF);
    fill(exits,0);
    state[a]=0;
    exits[a]=1;
    while (!t.empty())
    {
        int now=t.front();
        t.pop();
        for (int i=ls[now];i;i=e[i].next)
        {
            if (state[e[i].to]>state[now]+e[i].w)
            {
                state[e[i].to]=state[now]+e[i].w;
                if (!exits[e[i].to])
                {
                    exits[e[i].to]=1;
                    t.push(e[i].to);
                }
            }
        }
        exits[now]=0;
    }
}
int ans=0;
int dfs(int dep)
{
    exits[dep]=1;
    if (ans<state[b]) ans=state[b];
    for (int i=ls[dep];i;i=e[i].next)
    {
        if (!exits[e[i].to])
        {
            exits[e[i].to]=1;
            int f=state[e[i].to];
            state[e[i].to]=state[dep]+e[i].w;
            dfs(e[i].to);
            exits[e[i].to]=0;
            state[e[i].to]=f;
        }
    }
}
int main()
{
    scanf("%d%d%d",&n,&a,&b);
    int l=0;
    for (int i=1;i<=n;i++)
        for (int j=1;j<=n;j++)
        {
            int x;
            scanf("%d",&x);
            if (x!=0)
            {
                e[++l]=(edge){j,x,ls[i]}; ls[i]=l;
            }
        }

    dfs(a);
    if (ans==0) 
    {
        printf("-1\n");
        return 0;
    }

    else
    printf("%d\n",ans);
    spfa();
    if (state[b]==INF) printf("-1\n"); 
    else
    printf("%d\n",state[b]);

}