This page is still under construction.

Parts of this page are still being built. What you see may change.

Haywire

Interview

Time limit1sMemory limit128 MB

Summary
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 NN cows (4≤N≤124 \le N \le 12, NN 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 NN stalls lined up in a single row, one cow per stall. A wire of length LL requires exactly LL units of hay to build; for example, if the cows in stalls 4 and 7 are friends, the wire connecting them takes 33 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 NN. The cows are numbered 11 through NN.
  • Lines 2 through N+1N+1: line i+1i+1 contains three space-separated integers in the range 11 to NN, the three friends of cow ii. If cow ii is a friend of cow jj, then cow jj is also a friend of cow ii.

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 6,5,1,4,2,36, 5, 1, 4, 2, 3 is optimal and requires only 1717 units of hay.

Examples1

  1. Example 1

    Input
    6
    6 2 5
    1 3 4
    4 2 6
    5 3 2
    4 6 1
    1 5 3
    
    Expected output
    17