161772025-04-10 07:20:27RRoli2015. októbercpp17Time limit exceeded on test 53.084s7024 KiB
#include <bits/stdc++.h>
using namespace std;

struct Bencu{
    int x1, y1, x2, y2, tav;
};

int n, m, a[800][800], lk[800][800], x, y;
bool sz[800][800], van[800][800];
vector<Bencu> el;

void behuz(int x, int y) {
    if(x-1 >= 0 && lk[x-1][y] == -1) {
        Bencu szom = {x, y, x-1, y, abs(a[x][y] - a[x-1][y])};
        el.push_back(szom);
        van[x-1][y] = true;
    }
    if(x+1 < n && lk[x+1][y] == -1) {
        Bencu szom = {x, y, x+1, y, abs(a[x][y] - a[x+1][y])};
        el.push_back(szom);
        van[x+1][y] = true;
    }
    if(y-1 >= 0 && lk[x][y-1] == -1) {
        Bencu szom = {x, y, x, y-1, abs(a[x][y] - a[x][y-1])};
        el.push_back(szom);
        van[x][y-1] = true;
    }
    if(y+1 < m && lk[x][y+1] == -1) {
        Bencu szom = {x, y, x, y+1, abs(a[x][y] - a[x][y+1])};
        el.push_back(szom);
        van[x][y+1] = true;
    }
}

int main() {
    cin >> n >> m;
    for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) cin >> a[i][j];
    for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
        cin >> sz[i][j];
        if(sz[i][j]) {
            x = i;
            y = j;
        }
        lk[i][j] = -1;
    }

    lk[x][y] = 0; 
    behuz(x, y);
    van[x][y] = true;
    
    while(el.size() > 0) {
        for(int i = 0; i < el.size(); i++) {
            if(lk[el[i].x2][el[i].y2] != -1) {
                for(int j = i; j < el.size()-1; j++) el[j] = el[j+1];
                el.pop_back();
            }
        }
        if(el.size() == 0) break;
        
        int lk_ert = el[0].tav, lk_ind = 0;
        for(int i = 1; i < el.size(); i++) {
            if(el[i].tav < lk_ert && lk[el[i].x2][el[i].y2] == -1) {
                lk_ert = el[i].tav;
                lk_ind = i;
            }
        }
        lk[el[lk_ind].x2][el[lk_ind].y2] = max(lk[el[lk_ind].x1][el[lk_ind].y1], el[lk_ind].tav);

        int X = el[lk_ind].x2, Y = el[lk_ind].y2;

        for(int i = lk_ind; i < el.size()-1; i++) el[i] = el[i+1];
        el.pop_back();

        behuz(X, Y);
    }
    int ln = 0;
    for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
        if(sz[i][j]) ln = max(ln, lk[i][j]);
    }
    cout << ln;

	return 0;
}
1 - Accepted
Memory: 316KiB
Time: 1ms

Program's output:
21
Expected output:
21
Checker output:
ok 1 number(s): "21"

2 - Accepted
Memory: 316KiB
Time: 1ms

Program's output:
0
Expected output:
0
Checker output:
ok 1 number(s): "0"

3 - Accepted
Memory: 316KiB
Time: 1ms

Program's output:
1
Expected output:
1
Checker output:
ok 1 number(s): "1"

4 - Accepted
Memory: 316KiB
Time: 1ms

Program's output:
21
Expected output:
21
Checker output:
ok 1 number(s): "21"

5 - Time limit exceeded
Memory: 7024KiB
Time: 3.084s

Program's output:
Expected output:
9
Checker output: