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 84 85 86 87 88 89 90
|
#include <iostream> #include <climits> using namespace std;
int find_min_sum(int p[],int length){ unsigned short min = INT_MAX; for (int i = 0; i < length; i++) { unsigned short sum = 0; int left=i; int right=i; while (--left>=0 && p[i]==p[left]); while (++right<length && p[i]==p[right]); sum+=(right-left-1)*p[i]; while (left>=0 && right<length) { if(p[left]<p[right]){ sum+=2*p[left]; left--; } else if (p[left]>p[right]){ sum+=2*p[right]; right++; } else { sum+=2*p[right]; left--;right++; } } for (;right < length; right++) { sum+=2*p[right]; } for (;left>= 0; left--) { sum+=2*p[left]; } if (sum<min) { min=sum; } } return min;
} void test1(){ int a[6]={1,2,3,3,2,1}; if(12==find_min_sum(a,6)) cout<<"test1 ok"<<endl; } void test2(){ int a[6]={1,2,3,4,5,6}; if(36==find_min_sum(a,6)) cout<<"test2 ok"<<endl; } void test3(){ int a[4]={1,3,4,3}; if(12==find_min_sum(a,4)) cout<<"test3 ok"<<endl;
}
int main() { test1(); test2(); test3();
return 0; }
|