Saturday, April 26, 2014

Pretty Printing --- DP

Break texts into lines, each line no more than L characters.
Messness is measured as the blanks in each line, (suppose n) then sum 2^n together for all the line inlcuding the last line.

Code:

int find_pertty_printing(const vector &W, const int &L)
{
    //calculate M(i)
    vector M( W.size(), numeric_limits::max() );
    for (int i=0; i    {
        int b_len = L - W[i].size();
        M[i] = min( (i-1<0 b_len="" case="" for="" i-1="" i="" line="" m="" occupy="" one="" p="" the="" when="" word="">        for (int j=i-1; j>=0; --j)
        {
            b_len -= ( W[j].size() + 1);
            if (b_len < 0) break;
            M[i] = min( (j-1<0 0="" :="" b_len="" case="" for="" i="" j-1="" line="" m="" multiple="" occupy="" one="" p="" when="" word="">        }
    }

    // find the minimum cost without considering the last line
    long min_mess  = ( W.size() >= 2 ? M[W.size() - 2] : 0);
    int b_len = L - W.back().size();

    for (int i=W.size() - 2; i>=0; --i)
    {
        b_len -= (W[i].size() + 1);
        if (b_len <0 min_mess="" nbsp="" p="" return="">        min_mess  = min( min_mess, (i-1<0 0="" :="" i-1="" m="" p="">    }
    return min_mess;
}

No comments:

Post a Comment