Pagini recente » Cod sursa (job #1285651) | Cod sursa (job #1101909) | Cod sursa (job #1441010) | soldiers | Cod sursa (job #3040038)
#include <fstream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <map>
#include <set>
#include <cmath>
#include <algorithm>
#include <functional>
#include <cassert>
//#include <ext/pb_ds/assoc_container.hpp>
//using namespace __gnu_pbds;
using namespace std;
vector<int>rez;
struct cord
{
int y,x;
cord operator +(cord b)
{
return {b.y+y,b.x+x};
}
bool in(int n)
{
return (min(x,y)>=0 && max(x,y)<n);
}
int cash(int n)
{
return n*y+x;
}
};
class DSU
{
vector<set<int>>mp;
vector<int>t;
int root(int x)
{
if(t[x]!=x)t[x]=root(t[x]);
return t[x];
}
public:
DSU(int x)
{
mp=vector<set<int>>(x);
t=vector<int>(x);
for(int i=0;i<x;i++)
{
t[i]=i;
}
}
void insert(int val,int q)
{
mp[val].insert(q);
}
void unite(int x,int y,int val)
{
x=root(x);
y=root(y);
if(x==y)return;
if(mp[x].size()<mp[y].size())
{
swap(x,y);
}
t[y]=x;
for(auto &c:mp[y])
{
if(mp[x].count(c))
{
rez[c]=max(rez[c],val);
}
else
{
mp[x].insert(c);
}
}
}
};
vector<cord>dir={
{1,0},
{-1,0},
{0,1},
{0,-1}
};
void solve()
{
ifstream cin("matrice2.in");
ofstream cout("matrice2.out");
int n,q;
cin>>n>>q;
vector<vector<int>>a(n,vector<int>(n));
vector<cord>update(n*n);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
update[n*i+j]={i,j};
}
}
sort(update.begin(),update.end(),[&](cord x,cord y){
return a[x.y][x.x]>a[y.y][y.x];
});
DSU dsu(n*n);
for(int i=1;i<=q;i++)
{
cord g,h;
cin>>g.y>>g.x>>h.y>>h.x;
g.y--;
g.x--;
h.y--;
h.x--;
dsu.insert(g.cash(n),i);
dsu.insert(h.cash(n),i);
}
rez=vector<int>(q+1,-1);
for(auto c:update)
{
for(auto &v:dir)
{
auto aux=c+v;
if(aux.in(n) && a[c.y][c.x]<=a[aux.y][aux.x])
{
dsu.unite(c.cash(n),aux.cash(n),a[c.y][c.x]);
}
}
}
for(int i=1;i<=q;i++)
{
cout<<rez[i]<<'\n';
}
}
int32_t main()
{
function<string(bool)>sol=[&](bool x)
{
if(x)return "YES";
return "NO";
};
int _=1;
//cin>>_;
while(_--)
{
solve();
}
}