SERVICEH - Mobile Service Hard

no tags 

A company provides service for its partners that are located in different towns. The company has three mobile service staff employees. If a request occurs at some location, an employee of the service staff must move from his current location to the location of the request (if no employee is there) in order to satisfy the request. Only one employee can move at any moment. They can move only on request and are not allowed to be at the same location. Moving an employee from location p to location q incurs a given cost C(p,q). The cost function is not necessarily symmetric, but the cost of not moving is 0, i.e. C(p,p)=0. The company must satisfy the received requests in a strict first-come, first-serve basis. The goal is to minimize the total cost of serving a given sequence of requests.

Task

You are to write a program that decides which employee of the service staff is to move for each request such that the total cost of serving the given sequence of requests is as small as possible.

Input

The first line contains two integers, L and N. L (3 <= L <= 300) is the number of locations and N (1 <= N <= 3000) is the number of requests. Locations are identified by the integers from 1 to L. Each of the next L lines contains L non-negative integers. The jth number in the line i+1 is the cost C(i,j), and it is less than 2001.

The last line contains N integers, the list of the requests. A request is identified by the identifier of the location where the request occurs. Initially, the three service staff employees are located at location 1, 2 and 3, respectively.

Output

The first line contains one integer, M, the minimal total cost of serving the input sequence of the requests. The second line contains exactly N integers. The ith number is the identifier of the service staff employee (1, 2 or 3) who will serve the ith request. If there are multiple possibilities, your program should output one sequence only; it does not matter which one.

Example

Input:
5 9
0 1 1 1 1
1 0 2 3 2
1 1 0 4 1
2 1 5 0 1
4 2 3 4 0
4 2 4 1 5 4 3 2 1

Output:
5
1 2 1 2 2 1 3 1 3

hide comments
[Trichromatic] XilinX: 2010-02-18 14:20:44

It means you got "Memory Limit Exceeded". The memory limit of any SPOJ problem is exactly 256MB.

Angel Paredes: 2010-02-18 14:14:33

I'm getting "Runtime Error(other)",please can u tell me what kind of error it is, I don't see anything wrong in my code

Jakub Pachocki: 2010-01-03 16:35:56

Nice problem.

Last edit: 2010-01-02 02:33:58

Added by:Frane Kurtović
Date:2009-12-19
Time limit:1s-5.519s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: NODEJS OBJC PERL6 SQLITE VB.NET
Resource:CEOI 2005, Day 1