[编程题] 最大和 在一个N*N的数组中寻找所有横,竖,左上到右下,右上到左下,四种方向的直线连续D个数字的和里面最大的值
输入描述:
每个测试输入包含1个测试用例,第一行包括两个整数 N 和 D : 3 <= N <= 100 1 <= D <= N 接下来有N行,每行N个数字d: 0 <= d <= 100
输出描述:
输出一个整数,表示找到的和的最大值
输入例子:
4 2 87 98 79 61 10 27 95 70 20 64 73 29 71 65 15 0
输出例子:
193
代码虽然冗余,但是思路很清晰,四个大for循环,每个for循环求一个方向的所有和,这题想不到啥秒法,只有暴力循环啦><???
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int a[100][100];
bool isInmatrix(int n,int i,int j)
{
return i>=0&&i<n&&j>=0&&j<n;
}
int main()
{
int N,D;
cin>>N>>D;
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
cin>>a[i][j];
}
}
vector<int> vec;
for (int i = 0; i < N; ++i)
{
for (int start = 0; start <= N-D; ++start)
{
int sum=0;
for (int k = 0; k < D; ++k)
{
sum+=a[i][start+k];
}
vec.push_back(sum);
}
}
for (int i = 0; i < N; ++i)
{
for (int start = 0; start <= N-D; ++start)
{
int sum=0;
for (int k = 0; k < D; ++k)
{
sum+=a[start+k][i];
}
vec.push_back(sum);
}
}
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
int sum=0;
if(isInmatrix(N,i+D-1,j+D-1))
{
for (int k = 0; k < D; ++k)
{
sum+=a[i+k][j+k];
}
vec.push_back(sum);
}
}
}
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
int sum=0;
if(isInmatrix(N,i+D-1,j-D+1))
{
for (int k = 0; k < D; ++k)
{
sum+=a[i+k][j-k];
}
vec.push_back(sum);
}
}
}
sort(vec.begin(),vec.end());
cout<<vec[vec.size()-1]<<endl;
return 0;
}