Balancing


Task: Balancing

There are some number (C) of containers each of which can contain 0, 1, or 2 stones. You are to write a program which assigns all stones to the containers such that no container contains more than 2 stones and the following expression for IMBALANCE is minimized.

displaymath38

where:

tex2html_wrap_inline40
is the Container Mass of container i and is computed by summing the masses of the stones assigned to container i.
AM
is the Average Mass of the containers and is computed by dividing the sum of the masses of all stones by the number of containers (C).
Input

The first line contains two numbers. The first number ( tex2html_wrap_inline50 ) defines the number of containers and the second number ( tex2html_wrap_inline52 ) defines the number of stones. The second line of input will contain S integers representing the masses of the stones in the set. Each stone mass will be an integer value and will be delimited by a space.

Output

First print the assignment of the stones starting from container 1 to container C. Your program should then print "IMBALANCE = X" on the next line by itself where X is the computed imbalance of your stone assignments ( round to 2 places after decimal point ).

Sample Input

5 9
19 2 3 11 7 13 5 17 1
Sample Output

1: 0 19
2: 1 17
3: 2 13
4: 3 11
5: 5 7
IMBALANCE = 11.60
Explanation:
AM = (19+2+3+11+7+13+5+17+1)/9 = 8.7777
IMBALANCE = abs(0+19-AM)+abs(1+17-AM)+abs(2+13-AM)+abs(3+11-AM)+abs(5+7-AM)
abs(x) means absolute value of x
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
#include <bits/stdc++.h>
using namespace std;
int main(){
 int a,x,t,z,arr[11],i,j,temp,b,e,d,f,u;
 float am=0,am2,IMBALANCE=0;
 ifstream infile("rocks.txt");
 ofstream outfile("rocks2.txt");
 infile>>x;
    infile>>t;
    a=0;
    while (infile>>u){
     am+=u;
     arr[a]=u;
     a++;
 }
  am2=am/(t);
 f=t;
sort (arr,arr+a+1);
 for (d=0;d<x;d++) {
   outfile<<d+1<<": "<<arr[d]<<" "<<arr[t]<<endl;
   t--;
  }
for (e=0;e<x;e++){
 IMBALANCE+=fabs(arr[e-1]+arr[t+1-e]-am2);
 f--;
 outfile<<IMBALANCE;
}
}
Last edited on
Topic archived. No new replies allowed.