1
+ /* Linear programming by simplex method */
2
+ #include < iostream>
3
+ #include < iomanip>
4
+ #define ND 2
5
+ #define NS 2
6
+ #define N (ND+NS)
7
+ #define N1 (NS*(N+1 ))
8
+ using namespace std ;
9
+ void init (float x[],int n){
10
+ int i=0 ;
11
+ for (;i<n;i++) x[i] = 0 ;
12
+ }
13
+ int main (){
14
+ int i,j,k,kj,ki,bas[NS];
15
+ float a[NS][N+1 ],c[N],cb[NS],th[NS],
16
+ x[ND],cj,z,t,b,min,max;
17
+ /* Initializing the arrays to zero */
18
+ init (c,N); init (cb,NS);
19
+ init (th,NS); init (x,ND);
20
+ for (i=0 ;i<NS;i++) init (a[i],N+1 );
21
+ /* Now set coefficients for slack
22
+ variables equal to one */
23
+ for (i=0 ;i<NS;i++) a[i][i+ND] = 1.0 ;
24
+ /* Now put the slack variables in the basis */
25
+ for (i=0 ;i<NS;i++) bas[i] = ND+i;
26
+ /* Now get the constraints
27
+ and the objective function */
28
+ cout << " Enter the constraints" << endl;
29
+ for (i=0 ;i<NS;i++){
30
+ for (j=0 ;j<ND;j++)
31
+ cin >> a[i][j];
32
+ cin >> a[i][N];
33
+ }
34
+ cout << " Enter the objective function"
35
+ << endl;
36
+ for (j=0 ;j<ND;j++)
37
+ cin >> c[j];
38
+ cout << fixed;
39
+ /* Now calculate cj and identify the incoming variable */
40
+ while (1 ){
41
+ max = 0 ; kj = 0 ;
42
+ for (j=0 ;j<N;j++){
43
+ z = 0 ;
44
+ for (i=0 ;i<NS;i++)
45
+ z += cb[i]*a[i][j];
46
+ cj = c[j]-z;
47
+ if (cj > max){
48
+ max = cj; kj = j;}
49
+ }
50
+ /* Apply the optimality test */
51
+ if (max <= 0 ) break ;
52
+ /* Now calculate thetas */
53
+ max = 0 ;
54
+ for (i=0 ;i<NS;i++)
55
+ if (a[i][kj]!= 0 ){
56
+ th[i] = a[i][N]/a[i][kj];
57
+ if (th[i] > max) max=th[i];
58
+ }
59
+ /* Now check for unbounded soln. */
60
+ if (max <= 0 ){
61
+ cout << " Unbounded solution" ;
62
+ return 1 ;
63
+ }
64
+ /* Now search for the outgoing variable */
65
+ min = max; ki = 0 ;
66
+ for (i=0 ;i<NS;i++)
67
+ if ((th[i] < min)&&(th[i]!= 0 )){
68
+ min = th[i]; ki = i;
69
+ }
70
+ /* Now a[ki][kj] is the key element*/
71
+ t = a[ki][kj];
72
+ /* Divide the key row by key element*/
73
+ for (j=0 ;j<N+1 ;j++) a[ki][j] /= t;
74
+ /* Make all other elements of key column zero */
75
+ for (i=0 ;i<NS;i++)
76
+ if (i!= ki){
77
+ b = a[i][kj];
78
+ for (k=0 ;k<N+1 ;k++)
79
+ a[i][k]-=a[ki][k]*b;
80
+ }
81
+ cb[ki] = c[kj];
82
+ bas[ki] = kj;
83
+ }
84
+ /* Now calculating the optimum value */
85
+ for (i=0 ;i<NS;i++)
86
+ if ((bas[i] >= 0 ) && (bas[i]<ND))
87
+ x[bas[i]] = a[i][N];
88
+ z = 0 ;
89
+ for (i=0 ;i<ND;i++)
90
+ z += c[i]*x[i];
91
+ for (i=0 ;i<ND;i++)
92
+ cout << " x[" << setw (3 ) << i+1 << " ] = "
93
+ << setw (7 ) << setprecision (2 )
94
+ << x[i] << endl;
95
+ cout << " Optimal value = "
96
+ << setw (7 ) << setprecision (2 )
97
+ << z << endl;
98
+ return 0 ;
99
+ }
0 commit comments