前缀和 算法总结

一维前缀和

 

前缀和 算法总结
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cmath>
 4 #include<math.h>
 5 using namespace std;
 6 int a[1000010], s[1000010], m, n;
 7 int main()
 8 {
 9     s[0] = 0;
10     cin >> n >> m;
11     for (int i = 1; i <= n; i++)
12     {
13         cin >> a[i];
14         s[i] = s[i - 1] + a[i];
15     }
16     while (m--)
17     {
18         int l, r;
19         cin >> l >> r;
20         cout << s[r] - s[l - 1] << endl;
21     }
22     return 0;
23 }
View Code

 

 

二维前缀和

1 s[i][j] = s[i - 1][j] + s[i][j - 1] + a[i][j] - s[i-1][j-1];

 

 int x1, y1, x2, y2;
 cin >> x1 >> y1 >> x2 >> y2;
 cout << s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] +  s[x1-1][y1-1] << endl;

 

 

前缀和 算法总结
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cmath>
 4 #include<math.h>
 5 using namespace std;
 6 int a[1010][1010], s[1010][1010], m, n,q;
 7 int main()
 8 {
 9     s[0][0] = 0;
10     cin >> n >> m >> q;
11     for (int i = 1; i <= n; i++)
12     {
13         for (int j = 1; j <= m; j++)
14         {
15             cin >> a[i][j];
16             s[i][j] = s[i - 1][j] + s[i][j - 1] + a[i][j] - s[i-1][j-1];
17         }
18     }
19     while (q--)
20     {
21         int x1, y1, x2, y2;
22         cin >> x1 >> y1 >> x2 >> y2;
23         cout << s[x2][y2] - s[x2][y1 - 1] - s[x1 - 1][y2] +  s[x1-1][y1-1] << endl;
24 
25     }
26   
27     return 0;
28 }
View Code

 

上一篇:HENAU 冬令营 搜索专题 (A-L)


下一篇:直播系统源代码,选择验证方式时选择邮箱验证