Best Position
Time limit10sMemory limit256 MB
For each binary blueprint, find the placement with the most matching cells, tie-broken by row then column, and report the grain and livestock counts.
- Level
Medium7 of 10
- Topics
- String matching, Matrix, Brute force
- Solved
- No attempts yet
Problem
A farmer plans a new farm on a large field. The field is a grid with rows and columns, and each cell produces one kind of food: grain (G) or livestock (L). Here is a field with and .
12345678
1 GLGGLGLG
2 GGLGGLGL
3 GGLLLGGG
4 LLGLLGLG
5 LGGGLGLL
The farmer also has blueprints. A blueprint is a grid with rows and columns, where and . Each blueprint cell names the food the farmer wants in that spot, grain (G) or livestock (L). Here is a blueprint with and .
123
1 GLL
2 LGG
The farmer builds the farm by laying a blueprint on the field. The placement is named by the position of its top-left corner, so the blueprint covers field rows through and columns through . The whole blueprint has to fit inside the field, so and . For and , the field cell at produces food when its kind of food is the same as the kind in the blueprint cell at .
The farmer wants the placement that produces the most food, counting grain and livestock together. When several placements produce the same amount, he takes the one with the smallest , and among those the one with the smallest .
For the field and the blueprint above the best placement is . The blueprint then covers rows 1 to 2 and columns 3 to 5, where the field reads GGL on top and LGG below. Blueprint row GLL agrees with the field in the first and the third cell, producing 1 grain and 1 livestock. Blueprint row LGG agrees in all three cells, producing 2 grains and 1 livestock. The placement produces 5 foods, 3 grains and 2 livestock. Placements and also produce 5 foods, but has the smaller row number, and every other placement produces fewer than 5 foods.
Input
The input describes one field. The first line has two integers and (). Each of the next lines has characters and describes one row of the field.
The next line has one integer (), the number of blueprints the farmer has. Then come blueprints. Each blueprint starts with a line holding two integers and (, ), followed by lines of characters each.
Every character of the field and of the blueprints is either G or L.
Output
Print one line for each blueprint, in input order. For the blueprint numbered , counting from 1, print Case #X: followed by four integers separated by single spaces. The first two are the row and the column of the best position for the farm. The last two are the number of grains and the number of livestock produced at that position.