Haywire
InterviewTime limit1sMemory limit128 MB
Given a 3-regular graph on N cows (N at most 12), find the ordering of cows in a row minimizing the sum of pairwise distances between friends.
- Level
Medium7 of 10
- Topics
- Backtracking, Brute force, Graph
- Solved
- No attempts yet
Problem
Farmer John's cows (, even) have built a primitive system for communicating between pairs of friendly cows: each friendly pair is joined by a wire wrapped in hay.
Each cow has exactly 3 friends, and the cows arrange themselves to occupy stalls lined up in a single row, one cow per stall. A wire of length requires exactly units of hay to build; for example, if the cows in stalls 4 and 7 are friends, the wire connecting them takes units of hay.
Every pair of friends must be connected by a separate wire. Determine the minimum possible total amount of hay required if the cows order themselves in the best possible way.
Input
- Line 1: the integer . The cows are numbered through .
- Lines 2 through : line contains three space-separated integers in the range to , the three friends of cow . If cow is a friend of cow , then cow is also a friend of cow .
Output
- Line 1: the minimum total amount of hay required to connect all pairs of friendly cows.
Hint
Consider the case of 6 cows. Cow 1 is friends with cows 6, 2, and 5, and the rest are given similarly. Ordering the cows as is optimal and requires only units of hay.