列表

详情


NC252124. Components in Tree

描述

Given a tree with n nodes numbered from 1 to n.

Alice wants to know the number of connected components with a size of three in the tree.

输入描述

The first line contain a single integer n (1\leq n\leq 10^5), denoting the number of nodes in the tree.

In the next n-1 lines, each line contain two integers u and v (1\leq u,v\leq n), indicating that there is an edge between node u and node v.

输出描述

Output an integer in a single line, indicating the number of connected components with a size of three in the tree.

示例1

输入:

3
1 2
2 3

输出:

1

示例2

输入:

5
1 2
1 3
1 4
2 5

输出:

4

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

pypy3 解法, 执行用时: 430ms, 内存消耗: 57032K, 提交时间: 2023-05-22 22:05:16

n = int(input())
e = [ [] for i in range(n)]
for i in range(n-1):
    u,v = map(int,input().split())
    e[u-1].append(v-1)
    e[v-1].append(u-1)
ans = 0
for i in range(n):
    if len(e[i]) >= 2:
        ans += (len(e[i]) - 1)*len(e[i])//2
print(ans)

C 解法, 执行用时: 28ms, 内存消耗: 1084K, 提交时间: 2023-05-20 13:23:47

#include <stdio.h>
long long m[100010];
int main ()
{
	long long n,i,a,b,sum=0;
	scanf("%lld",&n);
	for(i=1;i<n;i++)
	{
		scanf("%lld%lld",&a,&b);
		m[a]++;
		m[b]++;
	}
	for(i=1;i<=n;i++)
		sum+=m[i]*(m[i]-1)/2;
	printf("%lld",sum);
	return 0;
}

C++(clang++ 11.0.1) 解法, 执行用时: 70ms, 内存消耗: 1176K, 提交时间: 2023-06-08 12:39:48

#include<bits/stdc++.h>
using namespace std;
long long n,ans;
long long a[100001];
int main()
{
	cin>>n;
	for(int i=1;i<n;i++)
	{
		int x,y;
		cin>>x>>y;
		a[x]++;
		a[y]++;
	}
	for(int i=1;i<=n;i++)
		ans+=a[i]*(a[i]-1)/2;
	cout<<ans;
}

Python3 解法, 执行用时: 522ms, 内存消耗: 5420K, 提交时间: 2023-06-25 16:30:35

n = int(input())
a = [0] * n

for i in range(n - 1):
    u, v = map(int, input().split())
    a[u - 1] += 1
    a[v - 1] += 1

ans = 0
for i in range(n):
    ans += a[i] * (a[i] - 1) // 2
print(ans)

上一题