#include #include #include #include using namespace std; int Sum(const vector & costs, int pivot, int length) { //cerr << "sum " << length << " at " << pivot << endl; int sum = 0; while(length--) sum += costs[pivot + length]; return sum; } int minAlign(int pivot, const vector & costs, int length) { //cerr << "align" << endl; int minCost = INT_MAX; for(int i = length; i--; ) minCost = min(minCost, Sum(costs, pivot - i, length)); return minCost; } int findPivot(const vector & costs) { //cerr << "pivot" << endl; int numPockets = costs.size()/3; vector maxs(1,0); for(int i = numPockets; i--; ) { const int index = i + numPockets; if(costs[index] == costs[maxs[0]]) maxs.push_back(index); else if(costs[index] > costs[maxs[0]]) maxs = vector(1, costs[index]); } //cerr << "pivot2" << endl; if(maxs.size() == 1) return maxs[0]; else { int bestMax = maxs[0]; int bestCost = INT_MAX; for(int i = maxs.size(); i--; ) { int cost = minAlign(maxs[i], costs, numPockets/2); if(cost < bestCost) { bestMax = maxs[i]; bestCost = cost; } } return bestMax; } } int main(int, char**) { int numPockets; while(cin >> numPockets) { if(numPockets == 0) break; vector costs(numPockets * 3); for(int i = 0; i < numPockets; i++) { int cost; cin >> cost; costs[i] = costs[i+numPockets] = costs[i+numPockets*2] = cost; } int pivot = findPivot(costs); int betLength = numPockets/2; int totalCost = minAlign(pivot, costs, betLength) + Sum(costs, pivot + 1, betLength) + Sum(costs, pivot - betLength, betLength); cout << totalCost << endl; } return 0; }