CSP试题 邻域均值
思路
采用动态规划算法
如果暴力解法的话,则时间复杂度为O(n2r2),肯定不会通过。我们采用动态规划:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
int averageValue(int n,int L,int r,int t,vector<vector<int>> graph) {
vector<vector<int>> f(n,vector<int>(n,0)); //f[i][j]表示以(i,j)点为中心的同一列的数之和
vector<vector<int>> g(n,vector<int>(n,0)); //g[i][j]表示以(i,j)点为中心的矩形的数之和
for(int j=0; j<n; j++) {
for(int i=0; i<r+0+1; i++) {
f[0][j]+=graph[i][j];
}
}
for(int i=1; i<n; i++) {
for(int j=0; j<n; j++) {
int temp_delete=0;
int temp_add=0;
if(i-r-1>=0) {
temp_delete=graph[i-r-1][j];
}
if(i+r<=n-1) {
temp_add=graph[i+r][j];
}
f[i][j]=f[i-1][j]-temp_delete+temp_add;
}
}
for(int i=0; i<r+1; i++) {
for (int j=0; j<r+1; j++) {
g[0][0]+=graph[i][j];
}
}
for(int i=1; i<n; i++) {
int temp_delete=0;
int temp_add=0;
if(i-r-1>=0) {
temp_delete=accumulate(graph[i-r-1].begin(),graph[i-r-1].begin()+r+1,0);
}
if(i+r<n) {
temp_add=accumulate(graph[i+r].begin(),graph[i+r].begin()+r+1,0);
}
g[i][0]=g[i-1][0]-temp_delete+temp_add;
}
for(int i=0; i<n; i++) {
for(int j=1; j<n; j++) {
int temp_delete=0;
int temp_add=0;
if(j-r-1>=0) {
temp_delete=f[i][j-r-1];
}
if(j+r<n) {
temp_add=f[i][j+r];
}
g[i][j]=g[i][j-1]+temp_add-temp_delete;
}
}
auto getCount=[&](int i,int j)->int {
int length=min(n-1,j+r)-max(0,j-r)+1;
int height=min(n-1,i+r)-max(0,i-r)+1;
return length*height;
};
int ans=0;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
int count=getCount(i,j);
if((double)g[i][j]/count<=t) {
ans++;
}
}
}
return ans;
}
};
int main() {
Solution solution;
int n,L,r,t;
cin>>n>>L>>r>>t;
vector<vector<int>> graph(n);
for(int i=0; i<n; i++) {
for (int j=0; j<n; j++) {
int temp;
cin>>temp;
graph[i].push_back(temp);
}
}
int res=solution.averageValue(n,L,r,t,graph);
cout<<res<<endl;
}