#include <iostream> #include "maklib.h" #include "message.h" #include <algorithm> using namespace std; int getMaxCrossingSubarray(int begin, int end, int k){ if(begin >= end) return 0; int a=0, b=0, s=0; for(int i=k; i>=begin; i--){ s += ElementAt(i); if(s > a) a = s; } s=0; for(int i=k+1; i<end; i++){ s += ElementAt(i); if(s > b) b = s; } return a+b; } int getMaxSubarray(int begin, int end){ if(begin >= end) return 0; int k = (begin+end)/2; int a = getMaxSubarray(begin, k); int b = getMaxSubarray(k+1, end); int c = getMaxCrossingSubarray(begin, end, k); if(a>=b && a>=c) return a; if(b>=c) return b; return c; } int main(){ int l = Size()/(NumberOfNodes()-1),ma,k,x; if(l==0) l=1; int a=min((MyNodeId()-1)*l, NumberOfNodes()-1); int b=min(MyNodeId()*l, NumberOfNodes()-1); int c=MyNodeId()/2; PutInt(c, a); PutInt(c, b); PutInt(c, getMaxSubarray(a,b)); Send(c); while(true){ x = MyNodeId()*2; if(x >= NumberOfNodes()) return 0; Receive(c); a = GetInt(x); b = GetInt(x); ma = GetInt(x++); k = (a+b)/2; if(x < NumberOfNodes()){ Receive(x); k = GetInt(x); b = GetInt(x); ma = max(ma, GetInt(x)); } x = max(ma, getMaxCrossingSubarray(a,b,k)); if(!MyNodeId() && a==1 && b==NumberOfNodes()-1){ cout<<x; return 0; } PutInt(c, a); PutInt(c, b); PutInt(c, x); Send(c); } return 0; }
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 | #include <iostream> #include "maklib.h" #include "message.h" #include <algorithm> using namespace std; int getMaxCrossingSubarray(int begin, int end, int k){ if(begin >= end) return 0; int a=0, b=0, s=0; for(int i=k; i>=begin; i--){ s += ElementAt(i); if(s > a) a = s; } s=0; for(int i=k+1; i<end; i++){ s += ElementAt(i); if(s > b) b = s; } return a+b; } int getMaxSubarray(int begin, int end){ if(begin >= end) return 0; int k = (begin+end)/2; int a = getMaxSubarray(begin, k); int b = getMaxSubarray(k+1, end); int c = getMaxCrossingSubarray(begin, end, k); if(a>=b && a>=c) return a; if(b>=c) return b; return c; } int main(){ int l = Size()/(NumberOfNodes()-1),ma,k,x; if(l==0) l=1; int a=min((MyNodeId()-1)*l, NumberOfNodes()-1); int b=min(MyNodeId()*l, NumberOfNodes()-1); int c=MyNodeId()/2; PutInt(c, a); PutInt(c, b); PutInt(c, getMaxSubarray(a,b)); Send(c); while(true){ x = MyNodeId()*2; if(x >= NumberOfNodes()) return 0; Receive(c); a = GetInt(x); b = GetInt(x); ma = GetInt(x++); k = (a+b)/2; if(x < NumberOfNodes()){ Receive(x); k = GetInt(x); b = GetInt(x); ma = max(ma, GetInt(x)); } x = max(ma, getMaxCrossingSubarray(a,b,k)); if(!MyNodeId() && a==1 && b==NumberOfNodes()-1){ cout<<x; return 0; } PutInt(c, a); PutInt(c, b); PutInt(c, x); Send(c); } return 0; } |