hdu 2437 Jerboas 最短路

解题思路:

这一题因为题目中“ 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;
}


你可能感兴趣的:(hdu 2437 Jerboas 最短路)