Highway Patrol

Time limit1sMemory limit128 MB

Summary
Choose a subset of directed edges to patrol, containing all forced edges and at least one edge, with equal patrolled in-degree and out-degree at every vertex, minimizing total patrol plus surveillance cost.
Level

Hard8 of 10

Topics
Graph, Dynamic programming, Shortest path, Greedy
Solved
No attempts yet

Problem

A city has NN base stations connected by MM one-way highways. Highway ii runs from station uiu_i to station viv_i. To keep the city safe, every highway must be monitored in exactly one of two ways:

  • Patrol it, at a cost of pip_i, or
  • Install video surveillance, at a cost of sis_i.

The patrol schedule has to stay balanced: at every base station, the number of patrolled highways that leave the station must equal the number of patrolled highways that enter it. In other words, the set of patrolled highways must form a circulation, so each station has equal patrolled out-degree and in-degree.

For security reasons some highways must be patrolled: if xi=1x_i = 1, highway ii has to be patrolled; if xi=0x_i = 0, either monitoring method is allowed.

Video surveillance may not replace patrolling completely, so at least one highway must be patrolled.

Determine the minimum possible total monitoring cost, or report that no valid schedule exists.

Input

The first line contains an integer TT (1≤T≤701 \le T \le 70), the number of test cases.

Each test case begins with a line containing two integers NN and MM (1≤N≤1001 \le N \le 100, 1≤M≤10001 \le M \le 1000), the number of base stations and highways. Each of the next MM lines contains five integers uu, vv, pp, ss, xx (1≤u,v≤N1 \le u, v \le N, 0≤p,s≤10000000 \le p, s \le 1000000, x∈{0,1}x \in \{0, 1\}): a highway from station uu to station vv with patrol cost pp, surveillance cost ss, and x=1x = 1 if the highway must be patrolled (otherwise x=0x = 0).

Output

For each test case print a line in the form Case i: c, where ii is the test case number (starting from 11) and cc is the minimum total monitoring cost. If no valid schedule exists, print Case i: impossible instead.

Examples3

  1. Example 1

    Input
    2
    4 5
    1 2 10 25 0
    2 3 10 5 0
    3 1 10 5 0
    2 4 10 5 0
    4 3 30 5 0
    4 5
    1 2 10 25 0
    2 3 10 5 0
    3 1 10 5 0
    2 4 10 5 0
    4 3 30 5 1
    
    Expected output
    Case 1: 40
    Case 2: 65
    
  2. Example 2

    Input
    1
    3 3
    1 2 1 10 0
    2 3 1 10 0
    3 1 1 10 0
    
    Expected output
    Case 1: 3
    
  3. Example 3

    Input
    1
    3 3
    1 2 10 1 0
    2 3 10 1 0
    3 1 10 1 0
    
    Expected output
    Case 1: 30