1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; const int maxn = 1000; int n; int fa[maxn], cnt[maxn]; int getRoot(int v) { if (fa[v] == v) return v; return getRoot(fa[v]); } int main() { cin >> n; for (int i = 0; i < n; ++i) { fa[i] = i; cnt[i] = 1; } int ans = 0; for (int i = 0; i < n - 1; ++i) { int a, b, x, y; cin >> a >> b; x = getRoot(a); y = getRoot(b); ans += cnt[x] * cnt[y]; fa[x] = y; cnt[y] += cnt[x]; } cout << ans << endl; return 0; } |
0 of 6 Questions completed
Questions:
You have already completed the quiz before. Hence you can not start it again.
Quiz is loading…
You must sign in or sign up to start the quiz.
You must first complete the following:
0 of 6 Questions answered correctly
Your time:
Time has elapsed
You have reached 0 of 0 point(s), (0)
Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)
1、输入的 a和 b 值应在 [0,n−1]的范围内。
2、第 16 行改成 fa[i] = 0;
,不影响程序运行结果。
3、若输入的 a 和 b 值均在[0,n−1] 的范围内,则对于任意 0≤i<n 都有 0≤fa[i]<n
4、若输入的 a 和 b 值均在 [0,n−1] 的范围内,则对于任意 0≤i<n 都有 1≤cnt[i]≤n
5、当 n 等于50时,若 a,b 的值都在 [0,49] 的范围内,且在第 25 行时 x 总是不等于 y,那么输出为
6、此程序的时间复杂度是?