终于把这道题补了,,拖了一个学期了,一直懒得去补。。
题目连接:http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1808
比普通的最短路,就是多了个换乘的花费,很自然的用 d[n][pre]代表从pre这条路到n这个点的最小时间花费,但第二维需要开多大那?d[1e5][1e5]?显然会爆,,因为有很多路是用不到的,所以又会很自然的想到,,可以只用vector保存有用的pre。。然后就是裸的dijikstra了
#include<iostream>
#include<stdio.h>
#include<queue>
#include<algorithm>
#include<string.h>
#define MX 111111
#define INF 0x3f3f3f3f
#define mem(x,y) memset(x,y,sizeof(x))
#define FIN freopen("input.txt","r",stdin)
using namespace std;
int n,m,s,t;
int head[MX],rear;
int num[MX];
vector<int> d[MX];
struct Edge
{
int to,nxt;
int c,dist;
int num;
} edge[2*MX];
struct Nod
{
int id,dist,c,num;
bool operator <(const Nod &a)const
{
return dist>a.dist;
}
Nod(int id,int dist,int c,int num):id(id),dist(dist),c(c),num(num) {}
};
void edge_init()
{
mem(head,-1);
rear=0;
}
void edge_add(int a,int b,int c,int dist,int x)
{
edge[rear].dist=dist;
edge[rear].nxt=head[a];
edge[rear].to=b;
edge[rear].c=c;
edge[rear].num=x;
head[a]=rear++;
}
int dijikstra()
{
priority_queue<Nod> Q;
for(int i =0; i<d[1].size(); i++) d[1][i]=0;
for(int i=head[1]; ~i; i=edge[i].nxt)
{
Q.push(Nod(edge[i].to,edge[i].dist,edge[i].c,edge[i].num));
d[edge[i].to][edge[i].num]=edge[i].dist;
}
while(!Q.empty())
{
Nod u=Q.top();
Q.pop();
if(u.id==n) return u.dist;
if(d[u.id][u.num]<u.dist) continue;
for(int i=head[u.id]; ~i; i=edge[i].nxt)
{
int v=edge[i].to;
if(d[v][edge[i].num]<=u.dist+edge[i].dist+abs(u.c-edge[i].c)) continue;
d[v][edge[i].num]=u.dist+edge[i].dist+abs(u.c-edge[i].c);
Q.push(Nod(v,d[v][edge[i].num],edge[i].c,edge[i].num));
}
}
return -1;
}
int main()
{
FIN;
int cas=0;
while(cin>>n>>m)
{
for(int i=1; i<=n; i++) d[i].clear();
edge_init();
mem(num,0);
for(int i=1; i<=m; i++)
{
int a,b,c,dist;
scanf("%d%d%d%d",&a,&b,&c,&dist);
edge_add(a,b,c,dist,num[b]++);
d[b].push_back(INF);
edge_add(b,a,c,dist,num[a]++);
d[a].push_back(INF);
}
printf("%d\n",dijikstra());
}
return 0;
}