题目链接:http://acm.scu.edu.cn/soj/problem.action?id=4554

Description

One day, Yutta and Rikka were playing a game. There were a N*M matrix. Every time Yutta picked up a submatrix which has w elements,
and then he asked Rikka, “Does every number between 1 and w occur in the submatrix ?”. Rikka was really not good at this game.
She felt dizzy after several rounds so she decide to ask your help.

Input

There will be multiple test cases.
For each case, the first line contains two numbers N, M(1 <= N, M <= 1000): the size of the matrix.
Then N lines follow. Each line has M numbers which indicates the matrix A.(1<=A[i][j]<=N*M).
The next line contains an integer Q(1 <= Q <= 100000): the number of the queries.
Then Q lines follow. Each line contains four integer x1, y1, x2, y2(1<=x1<=x2<=n, 1<=y1<=y2<=m) which indicate the submatrix.
More explicitly, (x1, y1) is the upper-left coordinate of the submatrix and (x2, y2) is the bottom-right coordinate of the submatrix.

Output

For each query, if the submatrix contains every number between 1 and w ouput “YES”, otherwise output “NO”.
w is the number of the submatrix’s elements.

Sample Input

3 3
1 2 5
3 4 6
7 8 9
7
1 1 1 1
1 1 2 2
1 1 2 3
1 1 3 3
1 1 3 2
1 1 2 1
1 1 1 2

Sample Output

YES
YES
YES
YES
NO
NO
YES

题意:判断一个小矩形a*b是否恰好由1-a*b这些数字组成,是输出YES,否则输出NO

解法:随机Hash。

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxm = 1e6 + 5;
const int maxn = 1e3 + 5;
LL mapping[maxm];
LL mappingsum[maxm];
LL g[maxn][maxn];
LL gen()
{
    LL ret = 0;
    for(int i = 0; i < 4; i++)
        ret = (ret << 16) | rand();
    return ret;
}
int main()
{
    srand(time(NULL));
    for(int i = 1; i < maxm; i++)
    {
        mapping[i] = gen();
        mappingsum[i] = mapping[i] ^ mappingsum[i - 1];
    }
    int n, m;
    while(~scanf("%d %d", &n, &m))
    {
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
            {
                int x;
                scanf("%d", &x);
                g[i][j] = g[i][j - 1] ^ mapping[x];
            }
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= m; j++)
                g[i][j] ^= g[i - 1][j];
        int q;
        scanf("%d", &q);
        while(q--)
        {
            int x1, y1, x2, y2;
            scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
            LL sum = g[x2][y2] ^ g[x1 - 1][y2] ^ g[x2][y1 - 1] ^ g[x1 - 1][y1 - 1];
            if(sum == mappingsum[(x2 - x1 + 1) * (y2 - y1 + 1)])
                printf("YES\n");
            else
                printf("NO\n");
        }
    }
}