PAT 1030. Travel Plan (30)

来源:互联网 发布:apache ab测试 linux 编辑:程序博客网 时间:2024/05/16 09:15

题目:http://www.patest.cn/contests/pat-a-practise/1030
考察最短路径问题,复习了一下dijkstra算法。
http://www.2cto.com/kf/201311/257005.html

题目不仅要求最短路径还需要加权值

#include<iostream>#include<cstdio>#include<cstring>using namespace std;int n,m,s,d;int highway[502][502];int cost[502][502];int INF = 10000000;bool flag[502];int dis[502];int c[502];int pre[502];int dijkstra()//dijkstra算法{    for(int i = 0; i < n; i++)    {        flag[i] = false;        dis[i] = highway[s][i];        c[i] = cost[s][i];        if(dis[i] == INF)            pre[i] = -1;        else            pre[i] = s;    }    dis[s] = 0;    flag[s] = true;    c[s] = 0;    for(int i = 0; i < n-1; i++)    {        int min = INF;        int pos;        for(int j = 0; j < n; j++)        {            if(!flag[j] && min >dis[j])            {                pos = j;                min = dis[j];            }        }        flag[pos] = true;        for(int j = 0; j < n; j++)        {            if(!flag[j])            {                if(dis[j] > (dis[pos]+ highway[pos][j]))                {                    dis[j] = dis[pos] + highway[pos][j];                    c[j] = c[pos] + cost[pos][j];                    pre[j] = pos;                }else if(dis[j] == (dis[pos]+ highway[pos][j]))                {                    if(c[j] > c[pos] + cost[pos][j])                    {                        c[j] = c[pos] + cost[pos][j];                        pre[j] = pos;                    }                }            }        }    }    return dis[d];}void searchPath()//打印路径{    int c = 0;    int path[502];    int x = 0;    path[x++] = d;    int temp = pre[d];    while(temp != s)    {        path[x++] = temp;        temp = pre[temp];    }    path[x] = s;    for(int i = x; i >= 0; i--)        printf("%d ",path[i]);}int main(){    while(scanf("%d%d%d%d",&n,&m,&s,&d) != EOF)    {        for(int i = 0; i < n; i++)        for(int j = 0; j < n; j++)        {            highway[i][j] = INF;            cost[i][j] = INF;        }        for(int i = 0; i < m; i++)        {            int a,b;            scanf("%d%d",&a,&b);            scanf("%d%d",&highway[a][b],&cost[a][b]);            highway[b][a] = highway[a][b];            cost[b][a] = cost[a][b];         }        int ans = dijkstra();        searchPath();        printf("%d %d\n",ans,c[d]);    }    return 0;}
0 0
原创粉丝点击