The degree of a vertex is the number of edges at it, and the degrees always add up to twice the number of edges. Your program computes the degrees of a graph and lists the odd ones.
What to build
A program that prints the degree of every vertex, their sum and the vertices of odd degree.
Requirements
- Read n and m, then m edges u v of a simple undirected graph on the vertices 1 to n.
- Print
degrees:and the degrees of the vertices 1 to n. - Print
sum:and the sum of all degrees. - Print
odd:and the vertices of odd degree in increasing order, ornone.
Input
The first line has n and m. Each of the next m lines has an edge.
Output
Three lines.
Constraints
1 ≤ n ≤ 20; 0 ≤ m ≤ 40.
Example
Input:
5 5
1 2
1 3
2 3
2 4
3 5
Output:
degrees: 2 3 3 1 1
sum: 10
odd: 2 3 4 5
Why it works
Each edge has two ends and adds 1 to the degree of each, so the degrees sum to 2m. A sum that is always even means the number of odd terms is even, so the list of odd vertices always has an even length.
Examples
5 5 1 2 1 3 2 3 2 4 3 5
degrees: 2 3 3 1 1 sum: 10 odd: 2 3 4 5
3 3 1 2 2 3 1 3
degrees: 2 2 2 sum: 6 odd: none
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Make a list of n zeros and add 1 to the entries of both ends of every edge.
Hint 2
The sum of the degrees should be twice the number of edges.
Hint 3
Vertices are numbered from 1; print `none` when there are no odd vertices.
Solution
Show one correct solution (try it yourself first)
n, m = map(int, input().split())
deg = [0] * (n + 1)
for _ in range(m):
u, v = map(int, input().split())
deg[u] += 1
deg[v] += 1
odd = [v for v in range(1, n + 1) if deg[v] % 2 == 1]
print("degrees:", *deg[1:])
print("sum:", sum(deg))
print("odd:", " ".join(map(str, odd)) if odd else "none")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step