唉,被求最小的字典序搞死了,如果用dijkstra很好实现,但是用spfa就只有用逆向的写法了。
#include<iostream>
#include<deque>
#include<vector>
#include<algorithm>
#include<list>
using namespace std;
const int maxn=1<<7;
const int inf=0x7fffffff;
int a[maxn][maxn];
int b[maxn];
int d[maxn];
bool hash[maxn];
int pre[maxn];
int N,x,y,temp;
int out[maxn];
deque<int>q;
inline void init()
{
for(int i=1;i<=N;i++)
{
d[i]=inf;
pre[i]=inf;
hash[i]=false;
}
d[y]=0;
q.clear();
return ;
}
void spfa()
{
q.push_front(y);
hash[y]=true;
while(!q.empty())
{
temp=q.back();
q.pop_back();
for(int i=1;i<=N;i++)
{
if(-1 == a[i][temp] || i==temp)
{
continue;
}
else
{
if( d[temp] + b[i] + a[i][temp] < d[i] )
{
d[i]=d[temp] + b[i] + a[i][temp];
pre[i]=temp;
if(hash[i]==false)
{
q.push_front(i);
hash[i]=true;
}
}
else if( d[temp] + b[i] + a[i][temp] == d[i] )
{
if(temp < pre[i])
{
pre[i]=temp;
}
}
}
}
hash[temp]=false;
}
out[0]=x;
temp=0;
while( pre[out[temp]] != inf )
{
out[temp+1]=pre[out[temp]];
temp++;
}
printf("From %d to %d :\nPath: ",x,y);
for(int i=0;i<temp;i++)
{
printf("%d-->",out[i]);
}
printf("%d\n",out[temp]);
printf("Total cost : %d\n\n",d[x]-b[x]);
return ;
}
int main()
{
while(cin>>N && N)
{
for(int i=1;i<=N;i++)
{
for(int j=1;j<=N;j++)
{
cin>>a[i][j];
}
}
for(int i=1;i<=N;i++)
{
cin>>b[i];
}
while(cin>>x>>y)
{
if(-1==x && -1==y)
{
break;
}
if(x!=y)
{
init();
spfa();
}
else
{
printf("From %d to %d :\n",x,y);
printf("Path: %d\n",x);
printf("Total cost : 0\n\n");
}
}
}
return 0;
}
分享到:
相关推荐
杭电hdu acm资料所用杭电的acm题
杭电 hdu acm 第1084题的解法,ac过了,是一位学长教我的.内有一些中文说明.
HDU_ACM培训课件(完整版) HDU_ACM培训课件(完整版) HDU_ACM培训课件(完整版) HDU_ACM培训课件(完整版)
hdu_2102_passed_sorce
此程序为hdu的acm2010题,就是解决水仙花数问题
模式识别_hdu_期末复习资料集合_试卷笔记.zip
HDU_ACM_1002_大数相加C源代码,利用字符串处理
数字图像处理_hdu_期末复习资料_试卷等.zip
数字图像处理总ppt_hdu_许老师.pdf
高级计算机图形学_mm的_重点笔记_hdu_吴xy.pdf
HDU一部分题目原码,大部分是可运行的,可能有几题不完整
B_(HDU_1231)(最大子段和,分治).cpp
(HDUACM2010版_06)并查集(最小生成树(HDUACM2010版_06)并查集(最小生成树(HDUACM2010版_06)并查集(最小生成树(HDUACM2010版_06)并查集(最小生成树
杭电acm解题报告 详细解析2000-2099 适合acm初学者
杭电OJ部分答案,可以很简单的解决a+b求和问题及其他问题。
For a positive integer n, let’s denote function f(n,m) as the m-th smallest integer x that x>n and gcd(x,n)=1. For example, f(5,1)=6 and f(5,5)=11. You are given the value of m and (f(n,m)?...
hdu题解的答案十分简单的一个题,思路清晰,特别简单
hdu 3378 三国杀标程 解题报告
动态规划DP题解 POJ HDU部分动态规划DP题解
基础算法类 ACM 入门 杭电OJ 11页题目题解,算法入门的时候刷题可以参考 搜集整理起来了比单个去搜题解方便快捷