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
| #include<cstdio> #include<vector> #include<queue> #include<utility> using namespace std;
vector<int> adjList[101]; pair<int, int> SPFA(int s, int tar); void path(int n, int now); int main() { int n, s, Case = 1; while (scanf("%d", &n) && n) { for (int i = 0; i <= n; i++) adjList[i].clear();
scanf("%d", &s); int v1, v2, count = 0; while (scanf("%d%d", &v1, &v2) && v1 && v2) adjList[v1].push_back(v2);
pair<int, int> ans = SPFA(s, n); printf("Case %d: The longest path from %d has length %d, finishing at %d.\n\n", Case++, s, ans.first, ans.second); }
return 0; } pair<int, int> SPFA(int s, int n) { int d[101] = {}; bool inQ[101] = {}; queue<int> Q; Q.push(s); while (!Q.empty()) { int next = Q.front(); Q.pop(); inQ[next] = false;
for (auto i : adjList[next]) { if (d[next] + 1 > d[i]) { d[i] = d[next] + 1; if (!inQ[i]) { Q.push(i); inQ[i] = true; } } } }
int max = 0, tar; for (int i = 1; i <= n; i++) if (max < d[i]) { max = d[i]; tar = i; }
return make_pair(max, tar); }
|