How can I avoid TLE in this code in c++?

조회 수: 1 (최근 30일)
Una Jacimovic
Una Jacimovic 2018년 7월 17일
댓글: Walter Roberson 2024년 9월 6일
it's counting sum of sub matrix: It works on every test except on last one.
#include <stdio.h>
int main() {
int a[1000][1000],m,n,i,j,d=0,M,N,H,S,s;
long int k,q;
scanf("%d%d",&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
scanf("%d",&q);
for(k=1;k<=q;k++)
{
s=0;
scanf("%d%d%d%d",&N,&M,&S,&H);
for(i=M;i<=M+H-1;i++)
for(j=N;j<=N+S-1;j++)
s+=a[i][j];
printf("%d\n",s);
}
  댓글 수: 1
Walter Roberson
Walter Roberson 2024년 9월 6일
Missing closing } corresponding to opening the function

댓글을 달려면 로그인하십시오.

답변 (1개)

BhaTTa
BhaTTa 2024년 9월 6일
To avoid a Time Limit Exceeded (TLE) error in your code, you need to optimize the way you calculate the sum of submatrices. The current approach of iterating over each submatrix for every query can be inefficient, especially for large matrices and numerous queries. Instead, you can use a technique called prefix sums to preprocess the matrix, allowing you to compute the sum of any submatrix in constant time.Steps to Optimize Using Prefix Sums
  1. Preprocess the Matrix:
  • Compute a prefix sum matrix where each element at position (i, j) contains the sum of all elements from the top-left corner (0, 0) to (i, j).
2. Compute Submatrix Sum Using Prefix Sums:
  • For each query, use the prefix sum matrix to calculate the sum of the submatrix efficiently.
Implementation in C++
Here's how you can implement this optimization:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
vector<vector<int>> a(m, vector<int>(n));
vector<vector<long long>> prefixSum(m + 1, vector<long long>(n + 1, 0));
// Input the matrix
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
// Build the prefix sum matrix
prefixSum[i + 1][j + 1] = a[i][j] + prefixSum[i][j + 1] + prefixSum[i + 1][j] - prefixSum[i][j];
}
}
int q;
cin >> q;
while (q--) {
int N, M, S, H;
cin >> N >> M >> S >> H;
// Adjust for 0-based index
N--; M--;
// Calculate the sum of the submatrix using the prefix sum matrix
long long s = prefixSum[M + H][N + S] - prefixSum[M][N + S] - prefixSum[M + H][N] + prefixSum[M][N];
cout << s << endl;
}
return 0;
}

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by