首页 > 代码库 > UVA 108 Maximum Sum

UVA 108 Maximum Sum

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=44

Dynamic Programming. 对所有可能存在的长方形计算sum,利用已知的小的sub-rectangle计算包含有这些相减或相加得到的new rectangle。代码如下:

 1 #include <iostream>
 2 #include <math.h>
 3 #include <stdio.h>
 4 #include <cstdio>
 5 #include <algorithm>
 6 #include <string.h>
 7 #include <string>
 8 #include <sstream>
 9 #include <cstring>
10 #include <queue>
11 #include <vector>
12 #include <functional>
13 #include <cmath>
14 #include <set>
15 #define SCF(a) scanf("%d", &a)
16 #define IN(a) cin>>a
17 #define FOR(i, a, b) for(int i=a;i<b;i++)
18 #define Infinity 999999999
19 typedef long long Int;
20 using namespace std;
21 
22 int main()
23 {
24     int N;
25     int num[105][105];
26     int sum[105][105];
27     while (SCF(N) != EOF)
28     {
29         FOR(i, 0, N + 1)
30             num[0][i] = num[i][0] = 0;
31         FOR(i, 1, N + 1)
32         {
33             FOR(j, 1, N + 1)
34                 SCF(num[i][j]);
35         }
36 
37         int maxSum = sum[0][0];
38         FOR(i, 0, N + 1)
39         {
40             FOR(j, 0, N + 1)
41             {
42                 sum[i][j] = num[i][j];
43                 if (i > 0)
44                     sum[i][j] += sum[i - 1][j];
45                 if (j > 0)
46                     sum[i][j] += sum[i][j - 1];
47                 if (i > 0 && j > 0)
48                     sum[i][j] -= sum[i - 1][j - 1];
49                 maxSum = max(maxSum, sum[i][j]);
50             }
51         }
52 
53         FOR(i, 0, (N+1)*(N+1))
54         {
55             int a = i / (N+1);
56             int b = i % (N + 1);
57             FOR(j, i+1, (N + 1)*(N + 1))
58             {
59                 int c = j / (N + 1);
60                 int d = j % (N + 1);
61                 if (c >= a && d >= b)
62                 {
63                     int csum = sum[c][d] - sum[c][b] - sum[a][d] + sum[a][b];
64                     maxSum = max(maxSum, csum);
65                 }
66             }
67         }
68         
69         printf("%d\n", maxSum);
70     }
71     return 0;
72 }

 

UVA 108 Maximum Sum