Wannafly模擬賽 矩陣 二維矩陣hash

霜刃未曾試發表於2017-08-30

題目:

https://www.nowcoder.com/acm/contest/submit/f8363c912a4c48a28b80f47e7102b6b8?ACMContestId=2&tagId=4

題意:

題目描述
給出一個n * m的矩陣。讓你從中發現一個最大的正方形。使得這樣子的正方形在矩陣中出現了至少兩次。輸出最大正方形的邊長。
輸入描述:
第一行兩個整數n, m代表矩陣的長和寬;
接下來n行,每行m個字元(小寫字母),表示矩陣;
輸出描述:
輸出一個整數表示滿足條件的最大正方形的邊長。

思路:

二維hash,先對每一行hash一次,然後在此基礎上對每一行hash一次

#include <bits/stdc++.h>

using namespace std;

typedef unsigned long long ull;
const int N = 500 + 10, INF = 0x3f3f3f3f;
const int seed = 131, Seed = 1789;
char ori[N][N];
ull hash1[N][N], seed_pow[N];
ull hash2[N][N], Seed_pow[N];
ull a[N*N];
int n, m;
bool check(int k)
{
    int tot = 0;
    for(int i = k; i <= n; i++)
    {
        for(int j = k; j <= m; j++)
        {
            ull tmp = hash2[i][j] - hash2[i-k][j] * Seed_pow[k] - hash2[i][j-k] * seed_pow[k] + hash2[i-k][j-k] * Seed_pow[k] * seed_pow[k];
            //ull tmp = hash2[i][j] - hash2[i-k][j] * Seed_pow[k] - (hash2[i][j-k] - hash2[i-k][j-k] * Seed_pow[k]) * seed_pow[k];
            a[++tot] = tmp;
        }
    }
    sort(a + 1, a + 1 + tot);
    for(int i = 1; i <= tot-1; i++)
        if(a[i] == a[i+1]) return true;
    return false;
}
int main()
{
    seed_pow[0] = Seed_pow[0] = 1;
    for(int i = 1; i < N; i++)
    {
        seed_pow[i] = seed_pow[i-1] * seed;
        Seed_pow[i] = Seed_pow[i-1] * Seed;
    }
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n; i++) scanf(" %s", ori[i] + 1);
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            hash1[i][j] = hash1[i][j-1] * seed + ori[i][j];
    for(int i = 1; i <= m; i++)
        for(int j = 1; j <= n; j++)
            hash2[j][i] = hash2[j-1][i] * Seed + hash1[j][i];
    int ans = 0;
    int l = 0, r = min(n, m);
    while(l <= r)
    {
        int mid = (l + r) >> 1;
        if(check(mid)) ans = mid, l = mid + 1;
        else r = mid - 1;
    }
    printf("%d\n", ans);
    return 0;
}

相關文章