White Day Present Exchange

Time limit1sMemory limit256 MB

Summary
Each student gives treats to one other student; choose whether each makes cookies or cake to maximize total happiness from what they receive.
Level

Hard8 of 10

Topics
Graph, Dynamic programming, Greedy, DFS
Solved
No attempts yet

Problem

Every year around White Day, JOI Academy holds a cookie and cake exchange. This year's exchange has N students, numbered 1 through N. Each student makes either cookies or a cake for exactly one other student. Student i gives BiB_i pieces of the treat they made to student AiA_i.

Some students want to receive the same kind of treat they made so they can study its taste, while others want to receive the other kind (cake if they made cookies, cookies if they made a cake) just for fun. Student i gains CiC_i points of "happiness" for each piece of the same kind of treat they made that they receive, and DiD_i points of "happiness" for each piece of the other kind they receive. If the N students choose well whether to make cookies or a cake, what is the largest possible total "happiness" of the N students?

Given each student's gift recipient and piece count, along with the "happiness" values, write a program to find the maximum total "happiness".

Input

Read the following input from standard input.

  • The first line contains the integer N, the number of students at JOI Academy.
  • Of the following N lines, line i (1 ≤ i ≤ N) contains the integers AiA_i, BiB_i, CiC_i, DiD_i separated by spaces. This means student i gives BiB_i pieces of treat to student AiA_i (1 ≤ AiA_i ≤ N, AiA_i ≠ i), gains CiC_i points of "happiness" per piece of the same kind of treat they made that they receive, and gains DiD_i points of "happiness" per piece of the other kind they receive.

Output

Print the maximum total "happiness" of the N students on one line to standard output.

Constraints

  • 2 ≤ N ≤ 100 000.
  • 1 ≤ BiB_i ≤ 1 000 000 (1 ≤ i ≤ N).
  • 1 ≤ CiC_i ≤ 1 000 000 (1 ≤ i ≤ N).
  • 1 ≤ DiD_i ≤ 1 000 000 (1 ≤ i ≤ N).

Examples1

  1. Example 1

    Input
    7
    3 3 6 5
    7 2 8 8
    4 5 3 9
    1 8 7 2
    1 8 8 4
    3 7 4 5
    2 5 1 2
    
    Expected output
    257