hdu 2437 Jerboas 最短路

本文介绍了一种利用SPFA算法解决特定条件下的迷宫最短路径问题的方法。针对有向无环图,通过结合节点和路径成本的状态表示技巧,有效地避免了传统DFS方法的超时问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:

这一题因为题目中“What's more, for some unknown reasons, it's true that start from any burrow, follows the tunnels you can not go back to the starting burrow. ”,所以该图一定是有向无环图,直接用DFS去找每个答案会超时,这题的n<=1000,k<=1000,将n和k结合起来作为作为新的状态,再用SPFA保证每次到达某个状态的花费是最小的,n*k<=1000000,SPFA的复杂度是够的。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<map>
#include<string>
#include<queue>
#include<vector>
#include<list>
//#pragma comment(linker,"/STACK:1024000000,1024000000")
using namespace std;
#define INF 0x3f3f3f3f
int n,m,s,k;
char str[1005];
typedef pair<int,long long> P;
struct edge{int to;long long cost;};
vector<edge> G[1005];
long long Min;
int Minp;
bool vis[1005000];
int dist[1005000];
bool SPFA(int start,int n)
{
    memset(vis,false,sizeof vis);
    fill(dist,dist+n+1,INF);
    vis[start]=true;
    dist[start]=0;
    queue<int> que;
    while(!que.empty()) que.pop();
    que.push(start);
    while(!que.empty())
    {
        int u=que.front();
        int pos=u/k;
        int r=u%k;
        que.pop();
        vis[u]=false;
        for(int i=0;i<G[pos].size();i++)
        {
            edge e=G[pos][i];
            if(dist[e.to*k+(r+e.cost)%k]>dist[u]+e.cost)
            {
                dist[e.to*k+(r+e.cost)%k]=dist[u]+e.cost;
                if(!vis[e.to*k+(r+e.cost)%k])
                {
                    vis[e.to*k+(r+e.cost)%k]=true;
                    que.push(e.to*k+(r+e.cost)%k);
                }
            }
        }
    }
    return true;
}
int main()
{
    int t,tt=0;
    scanf("%d",&t);
    while(t--)
    {

        scanf("%d%d%d%d",&n,&m,&s,&k);
        for(int i=0;i<=n;i++) G[i].clear();
        scanf("%s",str);
        for(int i=0;i<m;i++)
        {
            int u,v,c;
            scanf("%d%d%d",&u,&v,&c);
            G[u].push_back((edge){v,c});
        }
        Min=INF;
        Minp=-1;
        SPFA(s*k,n*k);
        for(int i=1;i<=n;i++)
        {
            if(str[i-1]=='P')
                if(dist[i*k]<Min) Min=dist[i*k],Minp=i;
        }
        printf("Case %d:",++tt);
        if(Min==INF) printf(" %d %d\n",-1,-1);
        else printf(" %I64d %d\n",Min,Minp);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值