#P16116. [USTCPC 2026] Doughnut

    ID: 18109 远端评测题 2000ms 512MiB 尝试: 0 已通过: 0 显示难度提高 上传者: 标签>图论广度优先搜索 BFS深度优先搜索 DFS2026高校校赛

[USTCPC 2026] Doughnut

Background

Today is another peaceful day. Kruskal-chan is in the library, struggling with graph theory.

Suddenly, a book called A Guide to Doughnut Planet fell off the shelf, with a note inside:

"Dear Kruskal-chan, we sincerely invite you to Doughnut Planet to help us compute n+mn+m! You remember all region adjacency relations, right?"

Huh? What is going on? Could it be that my graph theory skills have already spread across the universe?

Problem Description

The Doughnut people live on a doughnut-shaped planet. For easier management, the Doughnut King drew nn latitude circles (dotted lines in the figure) and mm longitude circles (dashed lines in the figure) on the planet, dividing the surface into nmnm regions, numbered from 11 to nmnm.

Kruskal is invited to visit Doughnut Planet. Since she has just learned graph theory, she remembers all region adjacency relations (i.e., which regions are adjacent). Can you help her compute the value of n+mn+m?

Doughnut Planet illustration

Input Format

This problem contains multiple test cases.

The first line contains an integer TT (1≤T≤1051\le T\le 10^5), the number of test cases.

For each test case, the first line contains an integer kk (0≤k≤1050\le k\le 10^5), the total number of region adjacency relations.

Then follow kk lines, each containing two integers u,vu,v, indicating that region uu is adjacent to region vv.

Note: The adjacency relations are guaranteed to be generated by some pair n,mn,m, but they may be given in any order.

It is guaranteed that ∑k≤105\sum k\le 10^5.

Output Format

Output TT lines. Each line contains one integer, the value of n+mn+m. If n+mn+m cannot be uniquely determined, output −1-1.

2
1
1 2
9
1 2
2 3
3 1
4 5
5 6
6 4
1 6
2 5
3 4
3
5

Hint

In the first sample, one of n,mn,m is 11 and the other is 22. It can be proven that no other possibility exists.

In the second sample, one of n,mn,m is 22 and the other is 33. It can be proven that no other possibility exists.

Translated by ChatGPT 5