算法导论16(贪心算法)

16.1 活动选择问题

void recursiveActivitySelector(vector<int> s,vector<int> f,int k,int n,vector<int> &res)
{
    int m=k+1;
    while(m<=n&&s[m]<f[k])++m;
    if(m<=n)res.push_back(m);
}

vector<int> greedyActivitySelector(vector<int> s,vector<int> f)
{
    int n=s.size();
    vector<int> A;
    A.push_back(1);
    int k=1;
    for(int m=2;m<=n;++m)
    {
        if(s[m]>=f[k])
        {
            A.push_back(m);
            k=m;
        }
    }
    return A;
}

16.2 贪心算法原理

16.3 赫夫曼编码

struct Node
{
    char val;
    int freq;
    Node *left,*right;
    Node(char x,int y):val(x),freq(y),left(NULL),right(NULL){}
};

bool cmp(Node *a,Node *b)
{
    return a->freq<b->freq;
}

Node *Huffman(vector<Node *> C)
{
    int n=C.size();
    vector<Node *> Q=C;
    for(int i=1;i<=n-1;++i)
    {
        Node *z=new Node('#',0),*x=NULL,*y=NULL;
        make_heap(Q.begin(),Q.end(),cmp);
        z->left=x=Q[0];
        Q.erase(Q.begin());
        make_heap(Q.begin(),Q.end(),cmp);
        z->right=y=Q[0];
        Q.erase(Q.begin());
        z->freq=x->freq+y->freq;
        Q.push_back(z);
    }
    return Q[0];
}

你可能感兴趣的:(算法导论16(贪心算法))