#include <iostream>
#include <vector>
#include <queue>
using namespace std;
class TreeNode{
public:
int num;
TreeNode *parent;
TreeNode *pair; ////node that appear in pair
vector<TreeNode*>childList;
TreeNode(int N){
num = N;
parent = nullptr;
pair = nullptr;
}
};
class Tree{
public:
int node_num;
TreeNode *root;
vector<TreeNode*> nodeList;
vector<TreeNode*> unconnectList; ////nodes that are not in the tree
Tree(int N, TreeNode *node){
node_num = N;
root = node;
}
bool Contain(int num){
for(auto & element: nodeList){
if(num == element->num){
return true;
}
}
return false;
}
TreeNode* Find(int num){
for(auto & element: nodeList){
if(num == element->num){
return element;
}
}
return nullptr;
}
};
void SelectionSort(vector<TreeNode*>& array){
for(int i = 0; i < array.size() - 1; i++){
int min = i;
for(int j = i + 1; j < array.size(); j++){
if(array[j]->num < array[min]->num)
min = j;
}
swap(array[i], array[min]);
}
}
int BFS(TreeNode* root){
int last_num = 0;
queue<TreeNode*>q;
vector<TreeNode*>v; ////level order list
q.push(root);
while(!q.empty()){
TreeNode* u= q.front();
v.push_back(u);
vector<TreeNode*> children = u->childList;
if(!children.empty()){
SelectionSort(children);
}
for(auto & node: children){
q.push(node);
}
q.pop();
}
last_num = v.back()->num;
return last_num;
}
int main() {
int sum = 0;
int T;
cin>>T;
for(int i = 0; i < T; i++){
int N; ////total N nodes
int R; ////Root number
cin>>N>>R;
TreeNode *root = new TreeNode(R);
Tree *T = new Tree (N, root);
T->nodeList.push_back(root);
for(int j = 0; j < N-1; j++){
int num1;
int num2;
cin>>num1>>num2;
////node1 has already in the tree, node2 not
////node1 is parent, add node2 to its child list
if(T->Contain(num1) && !T->Contain(num2)){
TreeNode *node2 = new TreeNode(num2);
T->Find(num1)->childList.push_back(node2);
node2->parent = T->Find(num1);
T->nodeList.push_back(node2);
}
else if(!T->Contain(num1) && T->Contain(num2)){
TreeNode *node1 = new TreeNode(num1);
T->Find(num2)->childList.push_back(node1);
node1->parent = T->Find(num2);
T->nodeList.push_back(node1);
}
else if(!T->Contain(num1) && !T->Contain(num2)){
TreeNode *node1 = new TreeNode(num1);
TreeNode *node2 = new TreeNode(num2);
T->unconnectList.push_back(node1);
T->unconnectList.push_back(node2);
node1->pair = node2;
node2->pair = node1;
}
}
////add unconnected nodes to the tree
for(auto &node: T->unconnectList){
if(T->Contain(node->num) && !T->Contain(node->pair->num)){
T->Find(node->num)->childList.push_back(node->pair);
node->pair->parent = T->Find(node->num);
T->nodeList.push_back(node->pair);
}
}
sum = sum + BFS(root);
}
cout<<sum<<endl;
return 0;
}