Fan migration
Time limit1sMemory limit256 MB
Assign every family to a house inside its own supporter block so the total compensation paid to families moving into cheaper houses is minimal.
- Level
Medium5 of 10
- Topics
- Graph
- Solved
- No attempts yet
Problem
Fans of two football teams, MC and MF, live in the town of M. The houses of the town stand along a single street and are numbered through . One family lives in each house.
The mayor is tired of the fights between the two sets of fans, so he has issued an edict that sends them to opposite ends of the street. The families who support MC must all move into houses through , and the families who support MF must all move into houses through . Every family that supports neither team moves into a house numbered through . Inside a block you may decide freely which family takes which house.
The mayor's assistants draw up a migration plan that meets those requirements. Every house has a price. A family that moves into a house cheaper than the one it used to live in receives compensation equal to the full price of its original house. A family that moves into a house of equal or higher price receives nothing. No family moves more than once.
Write a program that finds the smallest possible total compensation.
Input
The first line contains , the number of houses in the town. ()
Each of the next lines contains two integers, describing house through house in order. The first integer is the price of the house. The second integer tells which team the family living there supports: for neither team, for MC and for MF. At least one family in the town supports each of the two teams. Prices are positive integers no greater than .
Output
Print the smallest possible total compensation.
Hint
The first sample can be solved this way. The family in house moves to house and receives , the family in house moves to house and receives , and the family in house moves to house and receives nothing.
The second sample can be solved this way. The families in houses and swap houses and neither is compensated, and the family in house swaps with the family in house for a compensation of .