有了一张自驾旅游路线图,你会知道城市间的高速公路长度、以及该公路要收取的过路费。现在需要你写一个程序,帮助前来咨询的游客找一条出发地和目的地之间的最短路径。如果有若干条路径都是最短的,那么需要输出最便宜的一条路径。
输入格式:
输入说明:输入数据的第1行给出4个正整数N、M、S、D,其中N(2≤N≤500)是城市的个数,顺便假设城市的编号为0~(N−1);M是高速公路的条数;S是出发地的城市编号;D是目的地的城市编号。随后的M行中,每行给出一条高速公路的信息,分别是:城市1、城市2、高速公路长度、收费额,中间用空格分开,数字均为整数且不超过500。输入保证解的存在。
输出格式:
在一行里输出路径的长度和收费总额,数字间以空格分隔,输出结尾不能有多余空格。
输入样例:
4 5 0 3
0 1 1 20
1 3 2 30
0 3 4 10
0 2 2 20
2 3 1 20
输出样例:
3 40
今天新学了个spfa,有一说一,跟disjkstra堆优化很像
(dijkstra朴素)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 510;
int g[N][N];//存图
int dist[N];//存距离
int pre[N];//标记前一个点在哪
int ansp[N];//最大费用
int price[N][N];//费用
bool st[N];//记录每个点是否被遍历过
int n,m,s,d;
void dijkstra()
{
memset(dist,0x3f,sizeof dist);
memset(st,0,sizeof st);
dist[s] = 0;
ansp[s] = 0;
for(int i = 0;i < n;i++)
{
int t = -1;
for(int j = 0;j < n;j++)
{
if(!st[j] && (t ==-1 || dist[t] > dist[j]))
t = j;
}
st[t] = true;
for(int j = 0;j < n;j++)
{
if (dist[j] > dist[t] + g[t][j]) {
dist[j] = dist[t] + g[t][j];
ansp[j] = ansp[t] + price[t][j];
}
else {
if (dist[j] == dist[t] + g[t][j]) {
ansp[j] = min(ansp[t]+price[t][j],ansp[j]);
}
}
}
}
cout << dist[d] << ' ' << ansp[d] <<endl;
}
int main()
{
// cin>>n>>m>>s>>d;(scanf快一点)
scanf("%d%d%d%d",&n,&m,&s,&d);
memset(g,0x3f,sizeof g);
for(int i = 0;i < m;i++)
{
// int x,y,z,pri;
scanf("%d%d%d%d",&x,&y,&z,&pri);
g[x][y] = g[y][x] = z;
price[x][y] = price[y][x] = pri;
}
dijkstra();
}
cin输入
scanf输入
能用scanf就scanf吧,也没多几个单词。
(spfa)
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std ;
typedef pair<int , int > PII ;
const int N = 510 , M = N*N;
int price[N][N] ;
int st[N] ;
int dist[N] ;
int n , m , s , d ;
int ansp[N] ;
int h[N] , e[M] , ne[M] , idx , W[M];
void add(int a , int b ,int c )
{
W[idx] = c , e[idx] = b , ne[idx] = h[a] , h[a] = idx++ ;
}
void spfa()
{
memset(dist,0x3f,sizeof dist) ;
dist[s] = 0 ;
ansp[s] = 0 ;
queue<int> q ;
q.push(s);
st[s] = 1;
while(q.size())
{
int t = q.front() ;
q.pop();
st[t] = 0;
for(int i = h[t] ;~i ; i= ne[i] )
{
int j = e[i] ;
if(dist[j] > dist[t] + W[i] )
{
dist[j] = dist[t] + W[i];
ansp[j] = ansp[t] + price[t][j] ;
if(!st[j]){
q.push(j);
st[j]=true;
}
}
else
{
if(dist[j] == dist[t] + W[i] ){
if(ansp[j] > ansp[t] + price[t][j]){
ansp[j] = ansp[t] + price[t][j] ;
}
}
}
}
}
cout << dist[d] << " " << ansp[d]<<endl ;
}
int main()
{
memset(h, -1 , sizeof h ) ;
cin >> n >> m >> s >> d ;
for(int i = 0 ; i < m ; i ++ )
{
int a , b , w , pri;
cin >> a >>b >> w >> pri;
add(a, b ,w) , add(b,a ,w) ;
price[a][b] = price[b][a] = pri;
}
spfa() ;
return 0 ;
}