This problem also can be solved using Dynamic Programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
#include <iostream> #include <string> #include <cstring> #include <cstdio> using namespace std; string *str = new string [50]; int N; int kaadanealgo(int a,int b) { int line[50]; int max_end_here=0; int max_so_far=0; for(int i=0;i<N;i++) { line[i] = 0; for(int j=a;j<=b;j++) { if(str[j][i]=='0') line[i]+=-1000000; else line[i]+=(str[j][i]-'0'); } } for(int i=0;i<N;i++) { max_end_here+=line[i]; if(max_end_here<0) max_end_here = 0; if(max_end_here>max_so_far) max_so_far = max_end_here; } return max_so_far; } int main() { int t,m,mx; string s,a; bool c =false; cin>>t; getchar(); while(t--) { getline(cin,s); getline(cin,s); N = s.size(); int ind=0; str[0] = s; for(ind =1;ind<N;ind++) { getline(cin,s); str[ind]=s; } //N = str[0].size(); mx = 0; for(int i=0;i<ind;i++) { for(int j=i;j<ind;j++) { m = kaadanealgo(i,j); if(m>mx) mx = m; } } cout<<mx<<"\n"; if(t) cout<<"\n"; } return 0; } |
Similar problems are : uva 108, uva 10074,uva 10667; These can be solved using the same algorithm.