After decades of searching, you have finally given up on the eternal fame and glory for discovering the elusive Philosopher's Stone. However, you are still able to make a fortune producing gold, even without the Philosopher's Stone! For the right amount of money, alchemists will perform certain spells, transforming one element into another.
The world consists of
There are
Type
alchemists work with different elements. The -th of these elements is element , which has an associated trading value of . In one spell, they can convert any element from the set into another new element from that set, where the value of the spell is equal to the sum of the trading values of the old and new elements. More specifically, for any , with , they can turn element into element for a cost of . The base cost of the visit is equal to the sum of the values of the spells performed.Type
and type alchemists can perform different spells labelled from to . The -th spell converts element to element or vice-versa, where the value of the spell is . For type alchemists, the base cost of the visit is equal to the sum of the values of the spells performed. For type alchemists, the base cost of the visit is equal to the maximum of the values of the spells performed.
Furthermore, each time you visit the
Of course, there is no point in producing gold if it costs too much to produce it. What is the minimum possible final cost to transform your piece of iron into gold?
Constraints
It is guaranteed that every element is obtainable, starting with element
The elements that type 1 alchemists work with are pairwise distinct.
Subtask 1 [10%]
All alchemists are of type
Furthermore, for all
Subtask 2 [20%]
All alchemists are of type
Subtask 3 [70%]
No additional constraints.
Input Specification
The first line contains two space separated integers
The
The
If
Otherwise,
Output Specification
On a single line, print the minimum possible final cost of obtaining element
Sample Input
9 3
2 3 2
1 2 3
3 2 4
8 9 1
1 4 3
3 4 5 6
1 2 3 4
3 3 4
8 7 2
4 7 6
7 6 3
Sample Output
27
Explanation
To obtain gold (element
- Begin visiting alchemist
, incurring a visiting fee of . - Turn your element
into element , and then turn your element into element . The base cost of this visit is . - Finish visiting alchemist
. - Begin visiting alchemist
, incurring a visiting fee of . - Turn your element
into element . The base cost of this visit is . - Finish visiting alchemist
. - Begin visiting alchemist
, incurring a visiting fee of . - Turn your element
into element , and then turn your element into element . The base cost of this visit is . - Finish visiting alchemist
. - Begin another visit to alchemist
. Note that you will have to pay the visiting fee of again. - Turn your element
into element . The base cost of this visit is . - Finish visiting alchemist
.
The final cost is
Comments