File tree Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Original file line number Diff line number Diff line change 4545
4646### 動態規劃(DP)
4747 [[ d038]] ( https://zerojudge.tw/ShowProblem?problemid=d038 ) [[ 解答]] ( https://github.com/XassassinXsaberX/zerojudge/blob/master/uva/d038.c )
48+ [[ d206]] ( https://zerojudge.tw/ShowProblem?problemid=d206 ) [[ 解答]] ( https://github.com/XassassinXsaberX/zerojudge/blob/master/uva/d206.c ) (maximum subarray 2D)
4849 [[ d439]] ( https://zerojudge.tw/ShowProblem?problemid=d439 ) [[ 解答]] ( https://github.com/XassassinXsaberX/zerojudge/blob/master/uva/d439.c ) (質數表 + dp)
4950
5051
Original file line number Diff line number Diff line change 1+ #include <stdio.h>
2+ #include <stdlib.h>
3+
4+ /*
5+ maximum subarray的二維版
6+ 如果input matrix arr為
7+ 0 -2 -7 0
8+ 9 2 -6 2
9+ -4 1 -4 1
10+ -1 8 0 -2
11+ 我們把他當成
12+ 0 0 0 0 0
13+ 0 0 -2 -7 0
14+ 0 9 2 -6 2
15+ 0 -4 1 -4 1
16+ 0 -1 8 0 -2
17+
18+
19+ 經過dp的累積matrix變為
20+ 0 0 0 0 0
21+ 0 0 -2 -9 0
22+ 0 9 9 -4 -2
23+ 0 5 6 -11 -8
24+ 0 4 13 -4 -3
25+
26+ 例如dp[2][3] = arr[1][1] + arr[1][2] + arr[1][3]
27+ + arr[2][1] + arr[2][2] + arr[2][3]
28+
29+
30+
31+ 最後藉由dp matrix找最大區間
32+ 例如區間 arr[1][2] arr[1][3] arr[1][4]
33+ arr[2][2] arr[2][3] arr[2][4] 的總和
34+ 為dp[2][4] - dp[2][1] - dp[0][4] + dp[0][1]
35+
36+ */
37+
38+ int main ()
39+ {
40+ int N ;
41+ int arr [100 ][100 ];
42+ int dp [101 ][101 ];
43+ int i ,j ,k ,l ;
44+ int max ;
45+ while (scanf ("%d" ,& N )!= EOF )
46+ {
47+ for (i = 0 ;i < N ;i ++ )
48+ for (j = 0 ;j < N ;j ++ )
49+ scanf ("%d" ,& arr [i ][j ]);
50+ // 初始化dp matrix
51+ for (i = 0 ;i < N + 1 ;i ++ )
52+ for (j = 0 ;j < N + 1 ;j ++ )
53+ dp [i ][j ] = 0 ;
54+
55+ // 開始建立dp matrix
56+ for (i = 1 ;i < N + 1 ;i ++ )
57+ for (j = 1 ;j < N + 1 ;j ++ )
58+ dp [i ][j ] = arr [i - 1 ][j - 1 ] + dp [i ][j - 1 ] + dp [i - 1 ][j ] - dp [i - 1 ][j - 1 ];
59+
60+ // 從dp matrix找最大總和區間值
61+ max = -100000000 ;
62+ for (i = 1 ;i < N + 1 ;i ++ )
63+ for (j = 1 ;j < N + 1 ;j ++ )
64+ for (k = 0 ;k < i ;k ++ )
65+ for (l = 0 ;l < j ;l ++ )
66+ {
67+ if (dp [i ][j ] - dp [k ][j ] - dp [i ][l ] + dp [k ][l ] > max )
68+ max = dp [i ][j ] - dp [k ][j ] - dp [i ][l ] + dp [k ][l ];
69+ }
70+
71+ printf ("%d\n" ,max );
72+ }
73+
74+
75+ }
You can’t perform that action at this time.
0 commit comments