UVa11280

来源:互联网 发布:python pdf转html代码 编辑:程序博客网 时间:2024/06/08 07:22

题目链接

简介:
给出n个城市以及城市之间m条航线
每次询问给出一个s,表示在中转站不超过s的前提下,
从起点到终点的最短距离

分析:
显然又是dp+最短路
本来还想有优美的dijkstra解决,但是前辈说这道题Bellman的复杂度有更好一点
于是追求完美的我选择用Bellman-ford干了这道题

注意

起点和终点不算中转站

tip

s有可能超过点数

单向边

BEllman的队列中不需要传入dis,因为Bellman是在随时更新维护dis的,所以只需要这两维,在转移的时候,调用的是dis数组里的数据

我一开始加上了环的判定,结果一直WA
去掉就顺利的A了

//这里写代码片#include<cstdio>#include<cstring>#include<iostream>#include<queue>#include<vector>#include<map>#include<string>using namespace std;const int INF=0x33333333;int n,m,s,tot=0,S,T,q;string ss;map<string,int> mp;struct node{    int x,y,v;};struct heapnode{    int u,s;};struct Bellman{    int n,m;    vector<node> e;    vector<int> G[103];    bool in[103][103];    int dis[103][103];    void init(int n)    {        this->n=n;        e.clear();        for (int i=1;i<=n;i++) G[i].clear();    }    void add(int u,int w,int z)    {        e.push_back((node){u,w,z});        m=e.size();        G[u].push_back(m-1);    }    void Bell(int S)    {        memset(in,0,sizeof(in));        memset(dis,0x33,sizeof(dis));        dis[S][0]=0; in[S][0]=1;        queue<heapnode> Q;        Q.push((heapnode){S,0});       //不需要传入dis,因为Bellman是在随时维护dis的,所以只需要这两维        while (!Q.empty())        {            heapnode now=Q.front(); Q.pop();            int u=now.u;            int s=now.s;            in[u][s]=0;            for (int i=0;i<G[u].size();i++)            {                node way=e[G[u][i]];                if (dis[way.y][s+1]>dis[u][s]+way.v)                {                    dis[way.y][s+1]=dis[u][s]+way.v;                    if (!in[way.y][s+1])                    {                        in[way.y][s+1]=1;                        Q.push((heapnode){way.y,s+1});                    }                }            }        }    }};Bellman A;int main(){    int TT;    scanf("%d",&TT);    for (int cas=1;cas<=TT;cas++)    {        if (cas!=1) printf("\n");        mp.clear();        scanf("%d",&n);        A.init(n);        for (int i=1;i<=n;i++)        {            cin>>ss;            mp[ss]=i;        }        S=mp["Calgary"]; T=mp["Fredericton"];        scanf("%d",&m);        for (int i=1;i<=m;i++)        {            int u,w,z;            cin>>ss; u=mp[ss];             cin>>ss; w=mp[ss];            cin>>z;            A.add(u,w,z);        }        A.Bell(S);        scanf("%d",&q);        printf("Scenario #%d\n",cas);        while (q--)        {            scanf("%d",&s);            s=min(s,n);            int ans=INF;            for (int i=0;i<=s+1;i++)        //s可能大于点数                 ans=min(ans,A.dis[T][i]);            if (ans!=INF) printf("Total cost of flight(s) is $%d\n",ans);            else printf("No satisfactory flights\n");        }    }    return 0;}
原创粉丝点击