andmej / acm

My solutions for problems from the UVa Online Judge (Valladolid).

acm / 10000 - Longest Paths / 10000.2.cpp
100644 47 lines (39 sloc) 0.849 kb
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
/*
Time limit exceeded
*/
#include <queue>
#include <iostream>
#include <vector>
 
using namespace std;
 
int n, end, length;
 
void dfs(int u, int w, vector<int> * g){
  if (w > length){
    length = w;
    end = u;
  }
  vector<int> &vecinos = g[u];
  for (int i=0; i<vecinos.size(); ++i){
    dfs(vecinos[i], w + 1, g);
  }
}
 
int main(){
  int C = 1;
  while (cin >> n && n){
    int start;
    cin >> start, --start;
 
    vector<int> g[n];
    int p, q;
    while (cin >> p >> q && (p+q)){
      --p, --q;
      g[p].push_back(q);
    }
    for (int i=0; i<n; ++i){
      sort(g[i].begin(), g[i].end());
    }
 
    end = -1, length = -1;
    dfs(start, 0, g);
 
    cout << "Case " << C++ << ": The longest path from " << start + 1 << " has length ";
    cout << length << ", finishing at " << end + 1 << "." << endl << endl;
  }
  return 0;
}