#include #include #include #include using namespace std; typedef pair PIS; struct ReverseFirst { bool operator () (const PIS &a, const PIS &b) { if (a.first != b.first) return a.first > b.first; return a.second < b.second; } }; typedef set SS; typedef map MSSS; typedef set BIS; int count(MSSS &graph, string start, int depth) { if (depth == 0) return 1; SS &children = graph[start]; int total = 0; for (SS::iterator it = children.begin(); it != children.end(); ++it) { total += count(graph, *it, depth - 1); } return total; } int main(void) { int ncases; cin >> ncases; for (int casei = 1; casei <= ncases; ++casei) { int n, d; cin >> n >> d; MSSS graph; while (n--) { string curr; cin >> curr; int nchildren; cin >> nchildren; while (nchildren--) { string child; cin >> child; graph[curr].insert(child); } } BIS out; for (MSSS::iterator it = graph.begin(); it != graph.end(); ++it) { out.insert(PIS(count(graph, it->first, d), it->first)); } if (casei > 1) cout << endl; cout << "Tree " << casei << ":" << endl; int i = 0; int last_count = 0; for (BIS::iterator it = out.begin(); it != out.end(); ++it, ++i) { if (i >= 3 && it->first != last_count) break; if (it->first == 0) break; last_count = it->first; cout << it->second << ' ' << it->first << endl; } } return 0; }