Pagini recente » Cod sursa (job #2707704) | Cod sursa (job #897674) | Cod sursa (job #3238690) | Cod sursa (job #2609070) | Cod sursa (job #2629989)
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream cin("matrice2.in");
ofstream cout("matrice2.out");
const int NMAX = 300;
const int VALMAX = 1e6;
const int QMAX = 20000;
int N, Q;
int mat[NMAX + 2][NMAX + 2];
int pos[NMAX + 3][NMAX + 3];
bool active[NMAX * NMAX + 2];
int dad[NMAX * NMAX + 2];
vector <int> qr[NMAX * NMAX + 2];
vector <pair <int, int>> posval[VALMAX + 2];
int ans[QMAX + 2];
int dx[] = {-1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
int Root(int node)
{
if(node == dad[node])
return node;
return dad[node] = Root(dad[node]);
}
void dojoin(int p, int q, int val)
{
p = Root(p);
q = Root(q);
if(p == q)
return;
dad[q] = p;
vector <int> n;
int pp = 0, qq = 0;
while(pp < (int)qr[p].size() && qq < (int)qr[q].size())
{
if(qr[p][pp] < qr[q][qq])
n.push_back(qr[p][pp]), ++pp;
else
n.push_back(qr[q][qq]), ++qq;
}
while(pp < (int)qr[p].size())
n.push_back(qr[p][pp]), ++pp;
while(qq < (int)qr[q].size())
n.push_back(qr[q][qq]), ++qq;
vector <int> nn;
for(int i = 0; i < (int)n.size(); i++)
if(i > 0 && n[i] == n[i - 1])
{
ans[n[i]] = val;
nn.pop_back();
}
else
nn.push_back(n[i]);
qr[p] = nn;
n.clear();
qr[q].clear();
}
void join(pair <int, int> p)
{
int x = p.first, y = p.second;
active[pos[x][y]] = true;
for(int k = 0; k < 4; k++)
{
int xx = x + dx[k];
int yy = y + dy[k];
if(active[pos[xx][yy]])
dojoin(pos[x][y], pos[xx][yy], mat[x][y]);
}
}
int main()
{
cin >> N >> Q;
int k = 0;
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
{
cin >> mat[i][j];
++k;
pos[i][j] = k;
posval[mat[i][j]].push_back({i, j});
}
for(int i = 1; i <= Q; i++)
{
int x, y, xx, yy;
cin >> x >> y >> xx >> yy;
qr[pos[x][y]].push_back(i);
qr[pos[xx][yy]].push_back(i);
}
active[0] = false;
for(int i = 1; i <= N * N; i++)
{
dad[i] = i;
active[i] = false;
sort(qr[i].begin(), qr[i].end());
}
for(int i = 1000000; i >= 1; i--)
for(auto it : posval[i])
join(it);
for(int i = 1; i <= Q; i++)
cout << ans[i] << '\n';
return 0;
}