UVA-11280 - Flying to Fredericton(dijkstra)

这几题dijkstra写的比较顺手啊!

题意:某人要旅行,他把地图上N个城市按照从近到远给出,他要从1飞到N,但是又因为直接飞费用会很昂贵,故他想通过一个程序在换航班不超过K次的情况下所花费用最小!

分析:因为题目给出的城市名,不利于我们构图,故,通过map映射将他们标号即可.这题还是一样,将每个点的状态都标识出来,V[u][k]表示飞到u点换了k次航班,然后用dijkstra计算最短路即可.

注意:这题有重边,故不能用邻接矩阵,要使用邻接表!

// File Name: 11280.cpp
// Author: Zlbing
// Created Time: 2013/4/18 11:31:29

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdlib>
#include<cstdio>
#include<set>
#include<map>
#include<vector>
#include<cstring>
#include<stack>
#include<cmath>
#include<queue>
using namespace std;
#define CL(x,v); memset(x,v,sizeof(x));
#define INF 0x3f3f3f3f
#define LL long long
#define REP(i,r,n) for(int i=r;i<=n;i++)
#define RREP(i,n,r) for(int i=n;i>=r;i--)

const int MAXN=105;
map<string,int> S;
int n,m;
struct Edge{
    int u,v,cost;
};
vector<Edge> edges;
vector<int> G[MAXN];
struct node{
    int u,cost,ti;
    bool operator <(const node& a)const{
        return cost>a.cost;
    }
};
int V[MAXN][15];
int dijkstra(int time)
{
    priority_queue<node> Q;
    Q.push((node){1,0,0});
    memset(V,-1,sizeof(V));
    V[1][0]=0;
    node t,tt;
    while(!Q.empty())
    {
        t=Q.top();
        Q.pop();
        if(t.u==n)return t.cost;
        int u=t.u;
        int cost=t.cost;
        int ti=t.ti;
        for(int i=0;i<G[u].size();i++)
        {
            Edge e=edges[G[u][i]];
            int v=e.v;
            if(ti+1<=time)
            {
                if(V[v][ti+1]==-1||V[v][ti+1]>t.cost+e.cost)
                {
                    tt.u=v;
                    tt.cost=t.cost+e.cost;
                    tt.ti=t.ti+1;
                    V[tt.u][tt.ti]=tt.cost;
                    Q.push(tt);
                }
            }
        }
    }
    return -1;
}
int main()
{
    int N;
    scanf("%d",&N);
    for(int cas=0;cas<N;cas++)
    {
        if(cas)
        printf("\n");
        printf("Scenario #%d\n",cas+1);
        scanf("%d",&n);
        char ch[30];
        char ch1[30];
        int c;
        S.clear();
        REP(i,1,n)
        {
            scanf("%s",ch);
            S[string(ch)]=i;
        }
        REP(i,1,n)G[i].clear();
        edges.clear();
        scanf("%d",&m);
        REP(i,1,m)
        {
            scanf("%s %s %d",ch,ch1,&c);
    //        printf("---%s---\n",ch);
    //        printf("---%s---\n",ch1);
            int a=S[string(ch)];
        //    printf("---a--%d---\n",a);
            int b=S[string(ch1)];
            edges.push_back((Edge){a,b,c});
            int m=edges.size();
            G[a].push_back(m-1);
        }
        int q;
        scanf("%d",&q);
        while(q--)
        {
            int time;
            scanf("%d",&time);
            int ans=dijkstra(time+1);
            if(ans==-1)
                printf("No satisfactory flights\n");
            else printf("Total cost of flight(s) is $%d\n",ans);
        }
    }
    return 0;
}

 

posted @ 2013-04-18 12:14  z.arbitrary  阅读(354)  评论(0编辑  收藏  举报