bzoj2657: [Zjoi2012]旅游(journey)
求树的直径 真是太神辣
1 #include<cstdio> 2 #include<cstring> 3 #include<cstdlib> 4 #include<algorithm> 5 #include<iostream> 6 7 using namespace std; 8 9 template<typename Q> Q &read(Q &x) { 10 static char c, f; 11 for(f = 0; c = getchar(), !isdigit(c); ) if(c == '-') f = 1; 12 for(x = 0; isdigit(c); c = getchar()) x = x * 10 + c - '0'; 13 if(f) x = -x; return x; 14 } 15 template<typename Q> Q read() { 16 static Q x; read(x); return x; 17 } 18 19 const int N(200000); 20 int n; 21 22 bool neighbor(int a, int b) { 23 return abs(a - b) == 1 || abs(a - b) == n - 1; 24 } 25 26 #include<map> 27 map<pair<int, int>, int> mp; 28 int ID(int u, int v) { 29 if(u > v) swap(u, v); 30 if(mp.count(make_pair(u, v))) return mp[make_pair(u, v)]; 31 return mp[make_pair(u, v)] = mp.size(); 32 } 33 34 int no[N]; 35 36 #include<vector> 37 vector<int> G[N]; 38 39 void AddEdge(int u, int v) { 40 G[u].push_back(v); 41 G[v].push_back(u); 42 } 43 44 int q[N], ql, qr, dep[N]; 45 46 void BFS(int s) { 47 ql = qr = 0; 48 memset(dep, 0, sizeof dep); 49 q[qr++] = s, dep[s] = 1; 50 while(ql < qr) { 51 int u = q[ql++]; 52 for(unsigned i = 0; i < G[u].size(); i++) { 53 int v = G[u][i]; 54 if(!dep[v]) { 55 q[qr++] = v; 56 dep[v] = dep[u] + 1; 57 } 58 } 59 } 60 } 61 62 int main() { 63 #ifdef DEBUG 64 freopen("in.txt", "r", stdin); 65 freopen("out.txt", "w", stdout); 66 #endif 67 68 scanf("%d", &n); 69 for(int i = 1; i <= n - 2; i++) { 70 int a[4]; 71 for(int j = 0; j < 3; j++) scanf("%d", a + j); 72 a[3] = a[0]; 73 for(int j = 0; j < 3; j++) { 74 if(!neighbor(a[j], a[j+1])) { 75 int id = ID(a[j], a[j+1]); 76 if(no[id]) AddEdge(no[id], i); 77 else no[id] = i; 78 } 79 } 80 } 81 82 BFS(1), BFS(q[qr - 1]); 83 printf("%d\n", dep[q[qr - 1]]); 84 85 return 0; 86 }
原文出处http://www.cnblogs.com/showson/