算法导论29(线性规划)

29.1 标准型和松弛型

标准型:

maximize:j=1ncjxjsubjectto:j=1naijxjbi,i=1,2,,mxj0,j=1,2,,n

松弛型:

z=v+jNcjxjxi=bijNaijxj,iB

29.3 单纯形算法

转动:
(1) Compute the coefficients of equation for new basic variable xe .

xl=bljN{e}aljxjalexexe=blalejN{e}aljalexj1alexlxe=b^ejN{e}{l}a^ejxj

(2) Compute the coefficients of the remaining constraints.

xi=bijN{e}aijxjaiexe(iB{l})xi=bijN{e}aijxjaie(b^ejN{e}{l}a^ejxj)xi=biaieb^ejN{e}(aijaiea^ej)xj(aiea^el)xl

(3) Compute the objective function.

z=v+jN{e}cjxj+cexez=v+jN{e}cjxj+ce(b^ejN{e}{l}a^ejxj)z=v+ceb^e+jN{e}(cjcea^ej)xj+(cea^el)xl

(4) Compute new sets of basic and nonbasic variables.

N^=N{e}{l}B^=B{l}{e}

struct slackForm
{
    unordered_set<int> N,B;
    vector<vector<double> > A;
    vector<double> b,c;
    double v;
};

slackForm pivot(slackForm s,int l,int e)
{
    slackForm s0;
    //Compute the coefficients of equation for new basic variable xe
    s0.b[e]=s.b[l]/s.A[l][e];
    for(unordered_set<int>::iterator j=s.N.begin();j!=s.N.end();++j)
    {
        if(*j!=e)s0.A[e][*j]=s.A[l][*j]/s.A[l][e];
    }
    s0.A[e][l]=1/s.A[l][e];
    // Compute the coefficients of the remaining constraints
    for(unordered_set<int>::iterator i=s.B.begin();i!=s.B.end();++i)
    {
        if(*i!=l)
        {
            s0.b[*i]=s.b[*i]-s.A[*i][e]*s0.b[e];
            for(unordered_set<int>::iterator j=s.N.begin();j!=s.N.end();++j)
            {
                if(*j!=e)s0.A[*i][*j]=s.A[*i][*j]-s.A[*i][e]*s0.A[e][*j];
            }
            s0.A[*i][l]=-s.A[*i][e]*s0.A[e][l];
        }
    }
    s0.A[e][l]=1/s.A[e][l];
    //Compute the objective function
    s0.v=s.v+s.c[e]*s0.b[e];
    for(unordered_set<int>::iterator j=s.N.begin();j!=s.N.end();++j)
    {
        if(*j!=e)s0.c[*j]=s.c[*j]-s.c[e]*s0.A[e][*j];
    }
    s0.c[l]=-s.c[e]*s0.A[e][l];
    //Compute new sets of basic and nonbasic variables
    s.N.erase(e);
    s.N.insert(l);
    s0.N=s.N;
    s.B.erase(l);
    s.B.insert(e);
    s0.B=s.B;
    return s0;
}

正式的单纯形算法:

z=v+jNcjxje=maxjN{cj|cj>0}xi=bijNaijxj(iB)xi=bijN{e}aijxjaiexel=miniB{biaie|aie>0}

vector<double> simplex(slackForm s)
{
    while(true)
    {
        double delta=0;
        int e=0;
        for(unordered_set<int>::iterator j=s.N.begin();j!=s.N.end();++j)
        {
            if(s.c[*j]>delta)
            {
                delta=s.c[*j];
                e=*j;
            }
        }
        if(e==0)break;
        delta=INT_MAX;
        int l=0;
        for(unordered_set<int>::iterator i=s.B.begin();i!=s.B.end();++i)
        {
            if(s.A[*i][e]>0)
            {
                double t=s.b[*i]/s.A[*i][e];
                if(t<delta)delta=t;
                l=*i;
            }
        }
        s=pivot(s,l,e);
    }
    vector<double> x(s.c.size()+1,0);
    for(int i=1;i<=s.c.size();++i)
    {
        if(s.B.find(i)!=s.B.end())x[i]=s.b[i];
    }
    return x;
}

你可能感兴趣的:(算法导论29(线性规划))