您的位置:首页 > 其它

洛谷P1266 速度限制

2017-08-11 17:32 239 查看
题目链接:https://www.luogu.org/problem/show?pid=1266

解题思路:

1.求最快路线类似于求最短路,想到用spfa解决。

2.和一般的spfa不同,本题的路径中是以距离/速度来更新答案的,并且速度存在两种情况,需要分别分析。

3.既然有了速度这个变量,我们需要用数组来储存记录速度,dis[i][j]表示从到i点时速度为j的最快路线。在更新最短路的时候判断一下速度是否为0,用不同的速度更新答案。

4.题目要求输出路径,需要记录点和速度,递归输出路径。

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#define pr pair<int,int>
using namespace std;
queue<pair<int,int> >q;
struct node{
int from,to,t,ds;
}list[505*505];
double dis[505][505];
bool v[255][505];
int n,m,k,s,ans,x,y,t,z,head[255],px[255][505],ps[255][505];
void add(int x,int y,int t,int z){
list[++s].from=head[x];
list[s].to=y;
list[s].t=t;
list[s].ds=z;
head[x]=s;
}
void spfa(){
memset(dis,66,sizeof dis);
v[1][70]=1;q.push(pr(1,70));dis[1][70]=0;
while(!q.empty()){
pr p=q.front();q.pop();
int x=p.first,y=p.second;v[x][y]=0;
for (int i=head[x];i;i=list[i].from){

if (list[i].t==0)
{
if (dis[list[i].to][y]>dis[x][y]+1.0*list[i].ds/y){
dis[list[i].to][y]=dis[x][y]+1.0*list[i].ds/y;
px[list[i].to][y]=x;
ps[list[i].to][y]=y;
if (!v[list[i].to][y]){
v[list[i].to][y]=1;
q.push(pr(list[i].to,y));
}
}
}
else {
int sp=list[i].t;
if (dis[list[i].to][sp]>dis[x][y]+1.0*list[i].ds/sp){
dis[list[i].to][sp]=dis[x][y]+1.0*list[i].ds/sp;
px[list[i].to][sp]=x;
ps[list[i].to][sp]=y;
if (!v[list[i].to][sp]){
v[list[i].to][sp]=1;
q.push(pr(list[i].to,sp));
}
}
}
}
}
}
void print(int a,int b)
{
if(a!=1)print(px[a][b],ps[a][b]);
printf("%d ",a-1);
}
int main(){
cin>>n>>m>>k;k++;
for (int i=1;i<=m;i++){
scanf("%d%d%d%d",&x,&y,&t,&z);
x++;y++;
add(x,y,t,z);
}
spfa();
double ans=1e30;int c;
for (int i=1;i<=500;i++){
if (ans>dis[k][i])
ans=dis[k][i],c=i;
}
print(px[k][c],ps[k][c]);
cout<<k-1;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spfa 分层图 图论