There is a funny car racing in a city with n junctions and m directed roads. The funny part is: each road is open and closed periodically. Each road is associate with two integers (a, b), that means the road will be open for a seconds, then closed for b seconds, then open for a seconds. . . All these start from the beginning of the race. You must enter a road when it’s open, and leave it before it’s closed again. Your goal is to drive from junction s and arrive at junction t as early as possible. Note that you can wait at a junction even if all its adjacent roads are closed.
Input
There will be at most 30 test cases. The first line of each case contains four integers n, m, s, t (1 ≤ n ≤ 300, 1 ≤ m ≤ 50, 000, 1 ≤ s, t ≤ n). Each of the next m lines contains five integers u, v, a, b, t (1 ≤ u, v ≤ n, 1 ≤ a, b, t ≤ 105 ), that means there is a road starting from junction u ending with junction v. It’s open for a seconds, then closed for b seconds (and so on). The time needed to pass this road, by your car, is t. No road connects the same junction, but a pair of junctions could be connected by more than one road.
Output
For each test case, print the shortest time, in seconds. It’s always possible to arrive at t from s.
Sample Input
3 2 1 3 1 2 5 6 3 2 3 7 7 6 3 2 1 3 1 2 5 6 3 2 3 9 5 6
Sample Output
Case 1: 20 Case 2: 9
最短路
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int MAX=1e5+100;
const int inf = 1<<29;
int e,n,m,s,t,head[MAX],nex[MAX],cost[MAX],a[MAX],b[MAX],pnt[MAX],dist[MAX];
bool vis[MAX];
queue<int> q;
void add(int u,int v,int c,int sa,int sb)
{
pnt[e] = v;
nex[e] = head[u];
cost[e] = c;
a[e] = sa;
b[e] = sb;
head[u] = e++;
}
int spfa(int st,int des)
{
int i,j;
for(i=0;i<=n;i++)
dist[i] = inf;
dist[st] = 0;
memset(vis,0,sizeof(vis));
q.push(st);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = 0;
for(i=head[u];i!=-1;i=nex[i])
{
int v = pnt[i];
int val = dist[u],s= dist[u];
val = val%(a[i]+b[i]);
if(val > a[i])
s += b[i] - (val-a[i]);
else if(a[i]-val < cost[i])
s+=b[i]+a[i]-val;
if(s+cost[i]<dist[v])
{
dist[v] = s+cost[i];
if(!vis[v])
{
q.push(v);
vis[v] = 1;
}
}
}
}
return dist[des];
}
int main()
{
int cas = 1;
while(scanf("%d%d%d%d",&n,&m,&s,&t) != EOF)
{
e = 0;
memset(head,-1,sizeof(head));
for(int i=0;i<m;i++)
{
int u,v,a,b,t;
scanf("%d%d%d%d%d",&u,&v,&a,&b,&t);
if(a>=t)
add(u,v,t,a,b);
}
printf("Case %d: %d\n",cas++,spfa(s,t));
}
return 0;
}