Agents
Time limit1sMemory limit128 MB
Given a directed graph of who unmasked whom and the bribe cost of some agents, find the minimum cost to bribe agents so arrests cascade to everyone, or the smallest unreachable, unbribable agent.
- Level
Medium7 of 10
- Topics
- Graph, DFS, Greedy, Implementation
- Solved
- No attempts yet
Problem
The country is overrun by agents from foreign secret services. They do not only steal secret information, they also spy on one another. We say that an agent unmasked an agent if has collected enough documents to have arrested.
Some agents take bribes: for a certain amount of money they hand over every document they hold. So by buying off some agents we can start a chain of arrests (arresting an agent gives us all of that agent's documents), and this chain can lead to the liquidation of every agent in the country.
Counterintelligence has given us the number of foreign agents in the country, who can be bribed and at what price, and which agents unmasked which. There are agents (), numbered from to .
Write a program that:
- reads the counterintelligence data from standard input,
- decides whether it is possible to bribe some agents so that the resulting chain of arrests liquidates every agent in the country, and if so computes the minimum total bribe cost; otherwise reports the number of an agent that can neither be arrested nor bribed,
- writes the result to standard output.
Input
The first line contains one integer , the number of agents operating in the country ().
The second line contains one integer , the number of agents who take bribes (). Each of the next lines contains two integers: the number of an agent and the smallest bribe that agent will accept, which is at most .
The next line contains one integer (), the number of pairs such that agent unmasked agent . Each of the following lines contains two different integers from separated by a single space: the agent who did the unmasking, followed by the agent who was unmasked.
Output
On the first line print TAK (Polish for "yes") if it is possible to liquidate every agent in the country, or NIE (Polish for "no") otherwise.
- If it is possible, the second line must contain a single integer: the minimum total cost of bribing agents whose documents start a chain of arrests that liquidates every agent.
- If it is not possible, the second line must contain the number of an agent who can neither be arrested nor bribed. If several such agents exist, print the smallest number.