Pagini recente » Cod sursa (job #473752) | Cod sursa (job #613016) | Cod sursa (job #2691010) | Cod sursa (job #2210647) | Cod sursa (job #2715838)
#include <fstream>
#include <vector>
#include <algorithm>
std::ifstream fin("matrice2.in");
std::ofstream fout("matrice2.out");
const int N = 305;
const int Q = 2e4 + 5;
int n, q, x, y, a, b, cnt;
int Val[N*N];
int Dad[N*N];
int Solutie[Q];
struct Edge{
int cost, node;
bool operator<(const Edge& next) const { return cost>next.cost; }
};
struct Query{
int source, sink;
};
std::vector<Edge>g;
std::vector<Query>qu;
std::vector<std::pair<int, int>>ans;
int findDaddy(int node) {
if(node == Dad[node]) return node;
return (Dad[node] = findDaddy(Dad[node]));
}
bool isConnected(int node1, int node2) { return findDaddy(node1)==findDaddy(node2); }
void Unite(int node1, int node2) { Dad[findDaddy(node1)] = findDaddy(node2); }
void addAdjacent(int node) {
if(node-n>=0 and Val[node] <= Val[node-n]) Unite(node, node-n);
if(node%n<n-1 and Val[node] <= Val[node+1]) Unite(node, node+1);
if(node<(n-1)*n and Val[node] <= Val[node+n]) Unite(node, node+n);
if(node%n>0 and Val[node] <= Val[node-1]) Unite(node, node-1);
}
void Check(int k) {
int dp = 0;
for(int i=0;i<n*n;i++) Dad[i] = i;
std::sort(ans.begin(), ans.end(), std::greater<std::pair<int, int>>());
for(int i=0;i<ans.size();i++) {
while(dp < g.size() and g[dp].cost >= ans[i].first + (1<<k)) addAdjacent(g[dp].node), dp++;
if(isConnected(qu[ans[i].second].source, qu[ans[i].second].sink)) ans[i].first += (1<<k);
}
}
int tr(int x, int y) {
return (x-1) * n + y - 1;
}
void Solve() {
for(int i=20;i>=0;i--) Check(i);
for(int i=0;i<ans.size();i++) Solutie[ans[i].second] = ans[i].first;
for(int i=0;i<ans.size();i++) fout<<Solutie[i]<<"\n";
}
int main() {
fin>>n>>q;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
fin>>Val[tr(i, j)], g.push_back({Val[tr(i, j)], tr(i, j)});
std::sort(g.begin(),g.end());
//for(auto x:g) fout<<x.cost<<" "<<x.node<<"\n";
while(q--) {
ans.push_back({0, cnt++});
fin>>x>>y>>a>>b;
qu.push_back({tr(x, y), tr(a, b)});
}
Solve();
}