您的位置:首页 > 其它

最短路 ( SPFA )——Ramzi ( Gym 101061 C )

2016-08-14 09:50 344 查看
题目链接:

http://codeforces.com/gym/101061/problem/C

分析:

给出N个点和M条路,M条路有步行路有乘车路,给出每条路的种类和花费的时间,最后给出起点x和终点y,求从x到y的最短路(要求步行时间最小,步行时间相同时,要求总的时间最小)

题解:

很明显这是一道最短路,不过判断的标准从一个变成了两个,但是主要标准还是步行时间,我们就求步行时间的最短路,当步行时间相同的时候,更新一下总时间的最短路,一个SPFA即可求出。

注意:

路是双向的,判断的时候可以步行路写一种判断,乘车路写一种判断,以免混淆。

AC代码:



/*************************************************************************
> File Name: C.cpp
> Author: Akira
> Mail: qaq.febr2.qaq@gmail.com
> Created Time: 2016年08月13日 星期六 19时54分27秒
************************************************************************/

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cmath>
#include <vector>
#include <set>
#include <list>
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
#define MST(a,b) memset(a,b,sizeof(a))
#define CLR(a) MST(a,0)
#define Sqr(a) ((a)*(a))
#define bug cout<<pre[T]<<endl;
using namespace std;

#define MaxN 100000
#define MaxM MaxN*10
#define INF 1000000000

int Map[110][110];
int cost[110][110];
int N,M;
int S,T;

int tot[110];
int walk[110];
int vis[110];
struct cmp
{
bool operator() (int &a, int &b)
{
if(walk[a] == walk[b])
return tot[a]>tot[b];
return walk[a]>walk[b];
}
};

void SPFA()
{
for(int i=0;i<=N;i++)
{
tot[i] = INF;
walk[i] = INF;
vis[i] = 0;
}
tot[S] = 0;
walk[S] = 0;
vis[S] = 1;
priority_queue<int, vector<int>, cmp > q;
q.push(S);
while(!q.empty())
{
int tmp = q.top();
q.pop();
vis[tmp] = 0;
for(int i=1;i<=N;i++)
{
if( Map[tmp][i] == 2)
{
if(walk[i] > walk[tmp])
{
tot[i] = tot[tmp] + cost[tmp][i];
walk[i] = walk[tmp];
if(!vis[i])
{
q.push(i);
vis[i] = 1;
}
}
if(walk[i] == walk[tmp])
{
if(tot[i] > tot[tmp]+cost[tmp][i])
{
tot[i] = tot[tmp] + cost[tmp][i];
if(!vis[i])
{
q.push(i);
vis[i] = 1;
}
}
}
}

if(Map[tmp][i] == 1)
{
if(walk[i] > walk[tmp] + cost[tmp][i])
{
walk[i] = walk[tmp] + cost[tmp][i];
tot[i] = tot[tmp] + cost[tmp][i];
if(!vis[i])
{
q.push(i);
vis[i] = 1;
}
}
if(walk[i] == walk[tmp]+cost[tmp][i] )
{
if(tot[i] > tot[tmp]+cost[tmp][i])
{
tot[i] = tot[tmp] + cost[tmp][i];
if(!vis[i])
{
q.push(i);
vis[i] = 1;
}
}
}
}
}
}
}

void init()
{
CLR(Map);
CLR(cost);
}

int main()
{
int t;
scanf("%d", &t);
while(t--)
{
init();
scanf("%d%d", &N, &M);
for(int i=0;i<M;i++)
{
int a,b,c,k;
scanf("%d%d%d%d", &a,&b,&c,&k);
if(Map[a][b]<k)
{
Map[a][b] = Map[b][a] = k;
cost[a][b] = cost[b][a] = c;
}
if(Map[a][b] == k)
{
if(cost[a][b] > c)
cost[a][b] = cost[b][a] = c;
}
}
scanf("%d%d", &S, &T);
SPFA();
int ans = tot[T];
if(ans != INF)
cout << walk[T] << " " << tot[T] <<endl;
else
cout << -1 << endl;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  最短路 SPFA