先预处理。记录每个节点的直接父亲和直接儿子,父亲下属的儿子总数就是直接儿子数 + 直接儿子的儿子数。(最坏情况下预处理时间m ^ m / 2)
查询效率mq。
/* * Author: stormdpzh * Created Time: 2012/7/30 13:51:03 * File Name: poj_1634.cpp */ #include <iostream> #include <cstdio> #include <sstream> #include <cstring> #include <string> #include <cmath> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <algorithm> #include <functional> #define sz(v) ((int)(v).size()) #define rep(i, n) for(int i = 0; i < n; i++) #define repf(i, a, b) for(int i = a; i <= b; i++) #define repd(i, a, b) for(int i = a; i >= b; i--) #define out(n) printf("%d\n", n) #define mset(a, b) memset(a, b, sizeof(a)) #define wh(n) while(1 == scanf("%d", &n)) #define whz(n) while(1 == scanf("%d", &n) && n != 0) #define lint long long using namespace std; const int MaxN = 30005; struct Node { int id, salary, height; int father, sons; vector<int> vec; bool operator < (const Node &t) const { return salary < t.salary; } }node[MaxN]; int m, q; void init() { for(int i = 1; i <= m; i++) { scanf("%d%d%d", &node[i].id, &node[i].salary, &node[i].height); node[i].vec.clear(); node[i].father = 0; node[i].sons = 0; } sort(node + 1, node + 1 + m); for(int i = 1; i <= m; i++) { int j = i + 1; while(node[j].height < node[i].height && j <= m) j++; if(j <= m) { node[i].father = node[j].id; node[j].vec.push_back(i); node[j].sons++; } } for(int i = 1; i <= m; i++) { for(int j = 0; j < sz(node[i].vec); j++) { node[i].sons += node[node[i].vec[j]].sons; } } } void gao(int id) { for(int i = 1; i <= m; i++) { if(node[i].id == id) { printf("%d %d\n", node[i].father, node[i].sons); return ; } } } int main() { int t; scanf("%d", &t); while(2 == scanf("%d%d", &m, &q)) { init(); while(q--) { int id; scanf("%d", &id); gao(id); } } return 0; }