邻域均值 C++解法

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wumbuk

您的支持是我坚持的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值