Pilgrim's Memories and the Impressed God
Time limit8sMemory limit1024 MB
Given an N by N grid of 0 and 1 trials, sum X^2+1 over every distinct color string formed by monotone chains of sites, where X counts how often that string occurs.
- Level
Hard9 of 10
- Topics
- Dynamic programming, String, Combinatorics
- Solved
- No attempts yet
Problem
A pilgrim has been on a pilgrimage that seems like it will never end. There are holy sites on the earth. They are laid out in an grid, and the site in row from the top and column from the left is called site . A pilgrim who arrives at a site always receives either a black trial or a white trial. A black trial is a "trial of karma" that pays off one's sins, and a white trial is a "trial for ascent" that raises one's rank.
The pilgrim starts at site , called "the mortal world," and receives a trial there. After a trial at site , the pilgrim moves to site or and receives another trial. This repeats until the pilgrim reaches site , called "liberation," and receives the final trial. One pilgrimage visits sites in total.
In this way, there are different pilgrimages. To reach enlightenment, the pilgrim carried out every pilgrimage exactly once.
After all the pilgrimages, the resting pilgrim recalls them. A memory is a list of one or more sites in an order the pilgrim could have moved during a pilgrimage. Precisely, a memory of sites must satisfy all of the following: , , and for every .
For example, when , the pilgrim can recall 4 + 5 + 2 = 11 memories in total.

The benevolent and omnipotent god watched all of this and was deeply impressed. The god cares more about which trial was received than where it was received, so the god reads every site in the memories as the trial given there. After seeing all the memories, the god is impressed by for each memory that appears at least once, where is the number of times that memory appears. Find the total amount the god is impressed by.
Input
The first line contains a natural number , the size of the grid.
Each of the next lines contains a string of length made only of 0 and 1. The -th character of the -th line is 0 if site gives a black trial, and 1 if it gives a white trial.
Output
Print, on the first line, the total impression of the god modulo .