edgeremove

Edge Remove

There is a undirected connected graph with N nodes labelled from 1 to N. Each node i2 has an edge that connects i to ci. Note that ci<i and the same value of ci can appear no more than twice. Each node i also has a weight di.

You wish to remove all edges in the graph, however there is a cost incurred when removing a edge which is the sum of the weights of the nodes of the removed edge when the edge is removed. You can remove the edges in any order, however immediately after removing an edge the weights of the two ndoes that was connected to the edge are swapped.

Find the minimum cost needed to remove all the edges.

Limits

1N5000
1di109

Subtasks # Score Constraits
1 10 N10
2 20 N100
3 13 N500
4 24 N1000
5 33 -

Input format

The first line contains N.

The next line contains N integers, where the ith integer represents di

The next line contains N1 integers, where the ith integer represents ci+1

Output format

Output the minimum cost

Samples

Sample Input 1 Sample Output 1
3
2 1 3
1 1
7

An optimal solution is to disconnect nodes 1 and 2 for a cost of 2+1=3 and the weights are swapped so now node 1 has a weight of 1. Then disconnect nodes 1 and 3 for a cost of 1+3=4. Thus the total cost is 7.


Submitting .cpp to 'edgeremove'


You're not logged in! Click here to login

Time Limit: 5 Seconds
Memory Limit: 2048MB
Your best score: 0
Source: LOJ #3705

Subtask Score
1 10
2 20
3 13
4 24
5 33