標籤:style blog color os 2014 io
題目大意:在一個N * M的格子中,放有一些糖,這些糖有的會損害健康,有的對健康有益。有損害的被記為負數,有益的會記為正數。另外,對於每一個糖而言,他都比左邊的糖和上面的糖更健康。
現在我要在在N*M這個矩陣中找到一個子矩陣,使得所有糖的有益值加起來最大。
題目已經是簡化了的。糖果按照左上最小,右下最大的順序排列好了。所以很明顯從右下角的糖是肯定要拿走的,所以從這個格子開始枚舉。但是枚舉的話會逾時,該怎麼處理呢?
再想一下,發現題目不涉及更新操作,只有求和的部分。所以可以預先處理出所有的和,並存在對應的格子中。比如map[i][j]中存著 map[ 1..i ][ 1..j ]共計 i * j 個數的和。這樣只要遍曆所有格子,取出最大值就可以了。這樣演算法的複雜度就變成 O(nm)了。很明顯可以接受,而且寫法也簡單。
特別的,這裡可以有一些特殊處理,可以更方便的寫代碼。
例如輸入的時候從(m, n)開始輸入,讓最大值的位置變到左上方,最小值到右下角。
求和的時候一個一個累加過去 map[ i ][ j ] += map[ i ][ j-1 ],之後再 map[ i ][ j ] += map[ i–1 ][ j ]。這樣就能保證map[ i ][ j ]存的是其左上方的所有格子的和。
下面附上代碼:
/* * Problem: I * Date: 2014-7-20 * Author: Wuhen*/#include <map>#include <list>#include <queue>#include <string>#include <vector>#include <cstdarg>#include <stdio.h>#include <string.h>#include <stdlib.h>#include <iostream>#include <algorithm>#define LL __int64#define Clean(a) memset(a, 0, sizeof(a))using namespace std;LL ditu[1009][1009];LL max(LL a, LL b){ return ((a > b) ? a : b);}int main(){ std::ios::sync_with_stdio(false); LL n, m; LL T; scanf("%I64d", &T); while(T--) { scanf("%I64d%I64d", &n, &m); Clean(ditu); for (LL i = n; i > 0; i--) for (LL j = m; j > 0; j--) scanf("%I64d", &ditu[i][j]); for (LL i = 1; i <= n; i++) for (LL j = 2; j <= m; j++) ditu[i][j] += ditu[i][j-1]; for (LL i = 2; i <= n; i++) for (LL j = 1; j <= m; j++) ditu[i][j] += ditu[i-1][j]; LL res = ditu[1][1]; for (LL i = 1; i <= n; i++) for (LL j = 1; j <= m; j++) res = max(res, ditu[i][j]); printf("%I64d\n", res); } return 0;}