Cod sursă (job #446792)

Utilizator avatar KemyKo Teo Virghi KemyKo IP ascuns
Problemă Fotografie (clasele 9-10) Compilator cpp | 2,05 kb
Rundă Arhiva de probleme Status evaluat
Dată 14 mar. 2019 22:45:29 Scor 50
#include <cstdio>
#include <cstring>
#include <vector>
#define NMAX 1001

#define MOD 1000003
#define PRIM1 17
#define PRIM2 127

using namespace std;

typedef unsigned int ui;

ui n, m, p, q;
char A[NMAX][NMAX], B[NMAX][NMAX];
vector <ui> colHash;
ui hashA, hashB, auxHash, lineP = 1, colP = 1;

int main()
{
    ui i, j;
    freopen("fotografie.in",  "r", stdin);
    freopen("fotografie.out", "w", stdout);

    //read
    scanf("%d%d ", &n, &m);
    colHash = vector <ui> (m, 0);
    for(i=0; i<n; ++i)
        scanf("%s ", A[i]);

    scanf("%d%d ", &p, &q);
    for(i=0; i<p; ++i)
        scanf("%s ", B[i]);

    //PRIME ^ (SZ - 1)
    for(i=1; i<q; ++i) lineP = ((lineP << 7) - lineP);
    for(i=1; i<p; ++i) colP = ((colP << 4) + colP);

    //hashB
    for(j=0; j<q; ++j){
        //hash for col[i] from B
        auxHash = 0;

        for(i=0; i<p; ++i)
            auxHash = ((auxHash << 4) + auxHash) + (B[i][j] - '`');

        //hash the columns` hash ;)
        hashB = ((hashB << 7) - hashB) + auxHash;
    }

    //pre-hashing first m columns with p lines
    for(j=0; j<m; ++j)
        for(i=0; i<p; ++i)
            colHash[j] = ((colHash[j] << 4) + colHash[j]) + (A[i][j] - '`');

    //for each line calculate the new submatrix hash by moving left -> right
    for(i=0; i + p<=n; ++i){
        hashA = 0;

        //first submatrix hash using pre-hashes
        for(j=0; j<q; ++j)
            hashA = ((hashA << 7) - hashA) + colHash[j];

        if(hashA == hashB)
            printf("0 0\n");

        //move to the right
        for(j=q; j<m; ++j){
            auxHash = hashA - (colHash[j - q] * lineP);
            hashA   = ((auxHash << 7) - auxHash) + colHash[j];

            if(hashA == hashB)
                printf("%d %d\n", i, j - q + 1);
        }

        //prepare for moving down
        for(j=0; j<m; ++j){
            auxHash    = colHash[j] - ((A[i][j] - '`') * colP);
            colHash[j] = ((auxHash << 4) + auxHash) + (A[i + p][j] - '`');
        }
    }

    return 0;
}