[POJ 1847] Tram【SPFA】

  • 2018-01-03
  • 0
  • 0


Time Limit: 1000MS Memory Limit: 30000K


Tram network in Zagreb consists of a number of intersections and rails connecting some of them. In every intersection there is a switch pointing to the one of the rails going out of the intersection. When the tram enters the intersection it can leave only in the direction the switch is pointing. If the driver wants to go some other way, he/she has to manually change the switch.

When a driver has do drive from intersection A to the intersection B he/she tries to choose the route that will minimize the number of times he/she will have to change the switches manually.

Write a program that will calculate the minimal number of switch changes necessary to travel from intersection A to intersection B.


The first line of the input contains integers N, A and B, separated by a single blank character, 2 <= N <= 100, 1 <= A, B <= N, N is the number of intersections in the network, and intersections are numbered from 1 to N.

Each of the following N lines contain a sequence of integers separated by a single blank character. First number in the i-th line, Ki (0 <= Ki <= N-1), represents the number of rails going out of the i-th intersection. Next Ki numbers represents the intersections directly connected to the i-th intersection.Switch in the i-th intersection is initially pointing in the direction of the first intersection listed.


The first and only line of the output should contain the target minimal number. If there is no route from A to B the line should contain the integer "-1".

Sample Input

3 2 1
2 2 3
2 3 1
2 1 2

Sample Output



Croatia OI 2002 Regional - Juniors



一看就是最短路的模板题,理论上连 Floyd 都能过。

出于复习 SPFA 的目的,敲了一个十分优美丑陋的 SPFA,连 queue 都懒得手打。

Code: O(kE) [184K, 16MS]

using namespace std;

int N, A, B;

struct Edge{
	int np, cost;
	Edge *nxt;

struct Graph{
	Edge *V[102], E[10002];
	int tope;
	inline void clear() {tope = 0, memset(V, 0, sizeof(V));}
	inline void addedge(int u, int v, int w){
		E[++tope].np = v, E[tope].cost = w;
		E[tope].nxt = V[u], V[u] = &E[tope];
} G;

queue<int> q;
int dis[102];
bool inq[102];

inline void SPFA(){
	memset(dis, 0x3f, sizeof(dis)), dis[A] = 0;
	memset(inq, 0, sizeof(inq));
	q.push(A), inq[A] = 1;
		int u = q.front(), v;
		q.pop(), inq[u] = 0;
		for(register Edge *ne = G.V[u]; ne; ne = ne->nxt)
			if(dis[u] + ne->cost < dis[ne->np]){
				dis[ne->np] = dis[u] + ne->cost;
					inq[ne->np] = 1;

int main(){
	while(scanf("%d%d%d", &N, &A, &B) != EOF){
		for(register int i = 1; i <= N; i++){
			int K, v;
			scanf("%d", &K);
			for(register int j = 0; j < K; j++){
				scanf("%d", &v);
				if(j) G.addedge(i, v, 1);
				else G.addedge(i, v, 0);
		if(dis[B] < 0x3f3f3f3f) printf("%d\n", dis[B]);
		else puts("-1");
	return 0;



新博客地址: darkleafin.cf



OPEN AT 2017.12.10

Please refresh the page if the code cannot be displayed normally.


- Theme by Qzhai