30分求助
查看原帖
30分求助
685414
Wangsuyang楼主2025/1/20 16:05
#include<bits/stdc++.h>
using namespace std;
int arr[1005][1005];
int maxx[1005][1005];
int maxx1[1005][1005];
int minn[1005][1005];
int minn1[1005][1005];
deque<int> dq;
int main(){
	int a,b,n;
	cin>>a>>b>>n;
	for(int i = 1;i<=a;i++){
		for(int j = 1;j<=b;j++){
			cin>>arr[i][j];
		}
	}




	for(int i = 1;i<=a;i++){
		for(int j = 1;j<=b;j++){

			while(!dq.empty()&&j-dq.front()>=n) dq.pop_front();
			while(!dq.empty()&&arr[i][dq.back()]<arr[i][j]) dq.pop_back();
            dq.push_back(j);
			if(j>=n) maxx[i][j-n+1]=arr[i][dq.front()];
		}
		dq.clear();
	}
	for(int j = 1;j<=b-n+1;j++){
		for(int i = 1;i<=a;i++){
			while(!dq.empty()&&i-dq.front()>=n) dq.pop_front();
			while(!dq.empty()&&arr[dq.back()][j]<maxx[i][j]) dq.pop_back();
			dq.push_back(i);
			if(i>=n) maxx1[i-n+1][j]=maxx[dq.front()][j];
		}
		dq.clear();
	}



	for(int i = 1;i<=a;i++){
		for(int j = 1;j<=b;j++){

			while(!dq.empty()&&j-dq.front()>=n) dq.pop_front();
			while(!dq.empty()&&arr[i][dq.back()]>arr[i][j]) dq.pop_back();
            dq.push_back(j);
			if(j>=n) minn[i][j-n+1]=arr[i][dq.front()];
		}
		dq.clear();
	}
	for(int j = 1;j<=b-n+1;j++){
		for(int i = 1;i<=a;i++){
			while(!dq.empty()&&i-dq.front()>=n) dq.pop_front();
			while(!dq.empty()&&arr[dq.back()][j]>minn[i][j]) dq.pop_back();
			dq.push_back(i);
			if(i>=n) minn1[i-n+1][j]=minn[dq.front()][j];
		}
		dq.clear();
	}




	int r=INT_MAX;
	for(int i = 1;i<=a-n+1;i++){
		for(int j = 1;j<=b-n+1;j++){
			r=min(r,maxx1[i][j]-minn1[i][j]);
		}
	}

	cout<<r;
	return 0;
}
/*
5 4 2
1 2 5 6
0 17 16 0
16 17 2 1
2 10 2 1
1 2 2 2
*/

2025/1/20 16:05
加载中...