【Usaco2015 FEB】Cow Hopscotch (Gold)

Just like humans enjoy playing the game of Hopscotch, Farmer John's cows have invented a variant of the game for themselves to play. Being played by clumsy animals weighing nearly a ton, Cow Hopscotch almost always ends in disaster, but this has surprisingly not deterred the cows from attempting to play nearly every afternoon.

The game is played on an R by C grid (2 <= R <= 750, 2 <= C <= 750), where each square is labeled with an integer in the range 1..K (1 <= K <= R*C). Cows start in the top-left square and move to the bottom-right square by a sequence of jumps, where a jump is valid if and only if

1) You are jumping to a square labeled with a different integer than your current square,

2) The square that you are jumping to is at least one row below the current square that you are on, and

3) The square that you are jumping to is at least one column to the right of the current square that you are on.

Please help the cows compute the number of different possible sequences of valid jumps that will take them from the top-left square to the bottom-right square.

 

Input

The first line contains the integers R, C, and K. The next R lines will each contain C integers, each in the range 1..K.

 

Output

Output the number of different ways one can jump from the top-left square to the bottom-right square, mod 1000000007.

 

Sample Input

4 4 4
1 1 1 1
1 3 2 1
1 2 4 1
1 1 1 1

Sample Output

5



设f[i][j]表示到(i,j)的方案数,则有

f[i][j]=f[x][y](x<i,y<j,a[x][y]!=a[i][j])=f[x][y](x<i,y<j)f[x][y](x<i,y<j,a[x][y]==a[i][j])

采用分治,复杂度O(nmlogn)

然而考场上完全想不到用分治..

以后有题目束手无策时 就可以考虑分治&分块&二分来降低复杂度

下为代码

 

#include<bits/stdc++.h>
inline void read(int &x) {char c;while(!isdigit(c=getchar()));for(x = 0; isdigit(c); c = getchar()) x = x*10 + c-48;}

const int N = 751, P = 1e9 + 7;

int n, m, k;
int a[N][N], f[N][N], s[N*N];

inline void Solve(int L, int R)
{
    if(L == R) return ;
    int M = (L + R)>>1;
    Solve(L, M);
     memset(s, 0, 1+k << 2);
    for(int j = 1, all = 0; j <= m; ++ j) {
        for(int i = R; i > M; -- i)
            f[i][j] = ((f[i][j] + all - s[a[i][j]]) % P + P) % P;
        for(int i = L; i <= M; ++ i)
            (s[a[i][j]] += f[i][j]) %= P, (all += f[i][j]) %= P;
    }
    Solve(M+1, R);
}

int main()
{
    read(n), read(m), read(k);
    for(int i = 1; i <= n; ++ i)
        for(int j = 1; j <= m; ++ j)
            read(a[i][j]);
    f[1][1] = 1;
    Solve(1, n);
    printf("%d", f[n][m]);
}
View Code

 

posted @ 2016-02-21 16:30  jszyxw  阅读(296)  评论(0编辑  收藏  举报