-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path627-net.cpp
124 lines (101 loc) · 2.68 KB
/
627-net.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define pi acos(-1.0)
#define N 1000000
#define LL long long
#define For(i, a, b) for( int i = (a); i < (b); i++ )
#define Fors(i, sz) for( size_t i = 0; i < sz.size (); i++ )
#define Fore(it, x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++)
#define Set(a, s) memset(a, s, sizeof (a))
#define Read(r) freopen(r, "r", stdin)
#define Write(w) freopen(w, "w", stdout)
using namespace std;
int routers;
vector <int> matrix [300 + 5];
int parent [300 + 5];
int hop_count [300 + 5];
void reset ()
{
for ( int i = 0; i < 305; i++ ) {
parent [i] = i;
hop_count [i] = INF_MAX;
}
}
void bfs (int s, int t)
{
queue <int> q;
q.push (s);
hop_count [s] = 0;
while ( !q.empty () ) {
int p = q.front (); q.pop ();
if ( p == t ) return;
Fors (i, matrix [p]) {
if ( hop_count [matrix [p] [i]] == INF_MAX ) {
parent [matrix [p] [i]] = p;
hop_count [matrix [p] [i]] = hop_count [p] + 1;
q.push (matrix [p] [i]);
}
}
}
}
void print_path (int t)
{
vector <int> path;
path.push_back (t);
while ( parent [t] != t ) {
t = parent [t];
path.push_back (t);
}
reverse (path.begin (), path.end ());
printf ("%d", path [0]);
for ( size_t i = 1; i < path.size (); i++ ) printf (" %d", path [i]);
printf ("\n");
}
int main ()
{
//Read ("in.in");
//Write ("out.txt");
while ( scanf ("%d", &routers) != EOF ) {
getchar ();
for ( int i = 0; i < 305; i++ ) matrix [i].clear ();
for ( int i = 1; i <= routers; i++ ) {
char inp [1000]; gets (inp);
char *pch;
pch = strtok (inp, "-,");
int id = atoi (pch);
pch = strtok (NULL, "-,");
while ( pch != NULL ) {
int sees = atoi (pch);
matrix [id].push_back (sees);
pch = strtok (NULL, "-,");
}
}
int m; scanf ("%d", &m);
printf ("-----\n");
while ( m-- ) {
reset ();
int start, dest; scanf ("%d %d", &start, &dest);
bfs (start, dest);
if ( hop_count [dest] == INF_MAX ) printf ("connection impossible\n");
else print_path (dest);
}
}
return 0;
}