记录一个菜逼的成长。。
题目链接
这题跟pat(A)1111很像。。
只是在求最短路和最快的路的次要条件不一样并且输出格式颠倒一下。
之前写过pat(A)1111的代码
就稍微改下。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
#define cl(a,b) memset(a,b,sizeof(a))
#define pb push_back
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int maxn = 500 + 10;
int dist[maxn][maxn],tim[maxn][maxn];
int dis[maxn],Time[maxn],len[maxn],vis[maxn];
int path[maxn],path1[maxn];
void init(int n)
{
for( int i = 0; i < n; i++ ){
for( int j = 0; j < n; j++ ){
dist[i][j] = INF;
tim[i][j] = INF;
}
}
}
void dijkstra(int s,int n)
{
cl(vis,0);
cl(path,-1);
fill(len,len+n,INF);
len[s] = 0;
for( int i = 1; i < n; i++ ){
int x,mn = INF;
for( int j = 0; j < n; j++ ){
if(!vis[j] && mn > dis[j])mn = dis[x = j];
}
vis[x] = 1;
for( int j = 0; j < n; j++ ){
if(dis[j] > dis[x] + dist[x][j]){
dis[j] = dis[x] + dist[x][j];
len[j] = len[x] + 1;
path[j] = x;
}
else if(dis[j] == dis[x] + dist[x][j]){
if(len[j] > len[x] + 1){
len[j] = len[x] + 1;
path[j] = x;
}
}
}
}
}
void dijkstra1(int s,int n)
{
cl(vis,0);
cl(path1,-1);
fill(Time,Time+n,INF);
fill(dis,dis+n,INF);
dis[s] = 0;
Time[s] = 0;
for( int i = 1; i < n; i++ ){
int x,mn = INF;
for( int j = 0; j < n; j++ ){
if(!vis[j] && mn > Time[j])mn = Time[x = j];
}
vis[x] = 1;
for( int j = 0; j < n; j++ ){
if(Time[j] > Time[x] + tim[x][j]){
Time[j] = Time[x] + tim[x][j];
dis[j] = dis[x] + dist[x][j];
path1[j] = x;
}
else if(Time[j] == Time[x] + tim[x][j]){
if(dis[j] > dis[x] + dist[x][j]){
dis[j] = dis[x] + dist[x][j];
path1[j] = x;
}
}
}
}
}
int a[maxn],b[maxn];
int fun(int p[],int x,int st[])
{
int ind = 0;
while(x != -1){
st[ind++] = x;
x = p[x];
}
return ind;
}
bool check(int a[],int b[],int ind1,int ind2)
{
if(ind1 != ind2)return false;
for( int i = 0; i < ind1; i++ ){
if(a[i] != b[i])return false;
}
return true;
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m)){
init(n);
int u,v,flag,lenth,tm;
for( int i = 0; i < m; i++ ){
scanf("%d%d%d%d%d",&u,&v,&flag,&lenth,&tm);
dist[u][v] = lenth;
tim[u][v] = tm;
if(!flag){
dist[v][u] = lenth;
tim[v][u] = tm;
}
}
int s,e;
scanf("%d%d",&s,&e);
dijkstra1(s,n);//这里两个函数的调用不能变。根据题目意思,要先求最快,因为最短的条件是最快的次要条件,不然在求最短时会变化
dijkstra(s,n);
int ind1 = fun(path,e,a);
int ind2 = fun(path1,e,b);
if(check(a,b,ind1,ind2)){
printf("Time = %d; Distance = %d: ",Time[e],dis[e]);
for( int i = ind1 - 1; i >= 0; i-- ){
if(i == ind1 - 1){
printf("%d",a[i]);
}
else printf(" => %d",a[i]);
}
puts("");
}
else{
printf("Time = %d: ",Time[e]);
for( int i = ind2 - 1; i >= 0; i-- ){
if(i == ind2 - 1)printf("%d",b[i]);
else printf(" => %d",b[i]);
}
printf("\nDistance = %d: ",dis[e]);
for( int i = ind1 - 1; i >= 0; i-- ){
if(i == ind1 - 1)printf("%d",a[i]);
else printf(" => %d",a[i]);
}
puts("");
}
}
return 0;
}