- #include<iostream>
- #define N1 4
- #define N2 6
- #define INF -100000
- #define MAX 100000
- using namespace std;
- //约束条件系数
- double a[N1][N2] = {{0},{0,1,-2,1,0,0},
- {0,0,1,-3,1,0},
- {0,0,1,-1,0,1}};
- double b[N1] = {0,2,1,2}; // 向量b
- double e[N2] = {0,0,1,-2,0,0};//检验数向量
- double RHS = 0;//目标函数值
- int x[N1] = {0,0,0,0}; // 存放基本可行解
- // 找出初值解
- void BeginOne()
- {
- //进行列搜索, 得到初始解
- bool y[N2] = {0};
- //int num = 1;
- int index = 0;
- for(int j=1; j<N2; ++j){
- int cnt = 0;
- for(int i=1; i<N1; ++i)
- if(a[i][j]){
- ++cnt;
- index = i;
- }
- if(cnt==1&&y[j]==0){
- x[index] = j;
- y[j] = 1;
- }
- }
- cout<<"得到初始基本可行解为:"<<endl;
- for(int i=1; i<N1; ++i)
- cout<<"x("<<x[i]<<")"<<" = "<<b[i]/a[i][x[i]]<<endl;
- }
- void GetFirstForm()
- {
- double tmp = 0;
- for(int j=1; j<N1; ++j)
- if(e[x[j]]!=0){
- for(int i=1; i<N2; ++i){
- tmp = e[x[j]];
- e[i] -= tmp*a[j][i];
- }
- RHS -= tmp*b[j];
- }
- }
- int CheckVector()
- {
- bool IsNegative = 1;
- bool IsEnd = 1;
- for(int i=1; i<N2; ++i)
- if(e[i]>0){
- IsNegative = 0;
- for(int j=1; j<N1; ++j)
- if(a[j][i]>0)
- IsEnd = 0;
- if(IsEnd){
- cout<<"此LP问题×××!"<<endl;
- return 0;
- }
- }
- if(IsNegative){
- cout<<"迭代得到一个最优解:RHS = "<<RHS<<endl;
- for(int i=1; i<N1; ++i)
- cout<<"x("<<x[i]<<")"<<" = "<<b[i]/a[i][x[i]]<<endl;
- return 0;
- }
- return 1;
- }
- int MaxEj()
- {
- double max = INF;
- int index = 0;
- for(int i=1; i<N2; ++i)
- if(max<e[i]){
- max = e[i];
- index = i;
- }
- return index;
- }
- int main()
- {
- BeginOne();
- //得到第一张单纯行表
- GetFirstForm();
- cout<<"The First Form Of Simplex Method:"<<endl;
- cout<<"Vec ";
- for(int i=1; i<N2; ++i)
- cout<<e[i]<<" ";
- cout<<RHS<<endl;
- for(int i=1; i<N1; ++i){
- cout<<"x("<<x[i]<<") ";
- for(int j=1; j<N2; ++j)
- cout<<a[i][j]<<" ";
- cout<<b[i]<<endl;
- }
- /*循环得出最优解*/
- while(CheckVector()){
- int ej = MaxEj();
- double min = MAX;
- int Xiout = 0;
- //找到最小的b(i)/a(i)(ej)
- for(int i=1; i<N1; ++i)
- if(a[i][ej]>0&&min>b[i]/a[i][ej]){
- min = b[i]/a[i][ej];
- Xiout = i;
- }
- x[Xiout] = ej;
- for(int i=1; i<N2; ++i)
- if(ej!=i){ /*ej=Xiout Error Failed*/
- a[Xiout][i] = a[Xiout][i]/a[Xiout][ej];
- }
- /*Error will be found*/
- b[Xiout]/=a[Xiout][ej];
- a[Xiout][ej] = 1;
- //化检验数向量
- double tmp = e[ej];
- for(int i=1; i<N2; ++i)
- e[i] -= tmp*a[Xiout][i];
- RHS -= tmp*b[Xiout];
- for(int i=1; i<N1; ++i){
- if(i!=Xiout){
- tmp = a[i][ej];
- for(int j=1; j<N2; ++j)
- a[i][j] -= tmp*a[Xiout][j];
- b[i] -= tmp*b[Xiout];
- }
- }
- }
- system("pause");
- return 0;
- }
转载于:https://blog.51cto.com/hustluy/406683