hdu1385 最短路字典序

http://blog.csdn.net/ice_crazy/article/details/7785111

http://blog.csdn.net/shuangde800/article/details/8075165

http://www.cnblogs.com/qiufeihai/archive/2012/09/05/2672015.html

 

floyd可以更新任意两点之间的关系,path[i][j]记录的是i的直接后驱,输出时直接递推得到字典序路径

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <cctype>
#include <vector>
#include <iterator>
#include <set>
#include <map>
#include <sstream>
using namespace std;

#define mem(a,b) memset(a,b,sizeof(a))
#define pf printf
#define sf scanf
#define spf sprintf
#define pb push_back
#define debug printf("!\n")
#define MAXN 5010
#define MAX(a,b) a>b?a:b
#define blank pf("\n")
#define LL long long
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define pqueue priority_queue
#define INF 0x3f3f3f3f

int n;
int g[110][110],path[110][110];
int b[110],d[110][110];

void floyd()
{
    int i,j,k;
    int tmp;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            path[i][j] = j;
            d[i][j] = g[i][j];
        }
    }

    for(k=0;k<n;k++)
    {
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                tmp = d[i][k]+d[k][j]+b[k];
                if(d[i][j]>tmp)
                {
                    d[i][j] = tmp;
                    path[i][j] = path[i][k];
                }
                else if(tmp==d[i][j])
                {
                    if(path[i][j]>path[i][k])
                        path[i][j]=path[i][k];
                }
            }
        }
    }
}


int main()
{
    int i,j;
    while(sf("%d",&n)==1 && n)
    {
        mem(b,0);
        for(i=0;i<n;i++)
        {
            for(j=0;j<n;j++)
            {
                sf("%d",&g[i][j]);
                if(g[i][j] == -1)
                    g[i][j] = INF;
            }
        }
        for(i=0;i<n;i++)
            sf("%d",&b[i]);

        floyd();

        int s,t,tmp;
        while(sf("%d%d",&s,&t)==2)
        {
            if(s==-1 && t==-1) break;
            pf("From %d to %d :\n",s,t);
            pf("Path: %d",s);
            tmp=s-1;
            while(tmp!=t-1)
            {
                pf("-->%d",path[tmp][t-1]+1);
                tmp=path[tmp][t-1];
            }
            blank;
            pf("Total cost : %d\n\n",d[s-1][t-1]);
        }
    }
}

 

posted @ 2016-05-06 22:27  qlky  阅读(229)  评论(0编辑  收藏  举报