PTA 05-树9 Huffman Codes(Huffman 树构造,暴力判前缀)

题目链接

05-树9 Huffman Codes(30 分)

分析

Huffman树暴力判断就可

code

#include <bits/stdc++.h>

using namespace std;
#define MAXN 10100
#define INF 0x3f3f3f3f

typedef long long LL;

std::map<char, int> mp;
int n,m;

struct Node{
    char s;
    int val;
    Node *left;
    Node *right;
    Node(int v=0,char c=' ',Node * l=NULL,Node * r=NULL):val(v),s(c),left(l),right(r){};
    bool operator<(const Node o)const{
        return val > o.val;
    }
};
string s[64];
int bl=0;
void best_length(Node * root,int d=0){
    // cout << root -> val << " " << root->left <<" " <<root-> right<<"\n";
    if(root->left==NULL){
        bl+= d* mp[root->s];
        return;
    }
    best_length(root->left,d+1);
    best_length(root->right,d+1);
}

bool ok(int i1,int i2){
    if(s[i1].size() > s[i2].size())swap(i1,i2);
    for(int i=0 ; i<s[i1].size() ; ++i)
        if(s[i1][i]!= s[i2][i])return true;
    return false;
}
int main(int argc, char const *argv[]) {
    cin>>n;
    char buf[100];
    priority_queue<Node> Q;
    for(int i=0 ; i<n ; ++i){
        int x;
        scanf("%s %d", buf,&x);
        mp[buf[0]]=x;
        Q.push(Node(x,buf[0],NULL,NULL));
    }
    while (Q.size()>=2) {
        Node f1 = Q.top();Q.pop();
        Node f2 = Q.top();Q.pop();
        Node *left = new Node(f1.val,f1.s,f1.left,f1.right);
        Node *right = new Node(f2.val,f2.s,f2.left,f2.right);
        Q.push(Node(f1.val+f2.val,' ',left,right));
    }
    Node root = Q.top();
    // cout << root.val <<"\n";
    best_length(&root);
    // std::cout << bl << '\n';
    cin>>m;
    while (m--) {
        int len =0;
        for(int i=0 ; i<n ; ++i){
            string s1,s2;
            cin>>s1>>s[i];
            len += s[i].size() * mp[s1[0]];
        }
        // std::cout << len << '\n';
        if(len != bl)printf("No\n" );
        else{
            bool ans = true;
            for(int i=0 ; i<n && ans; ++i)
                for(int j=0 ; j<n ; ++j){
                    if(i==j)continue;
                    if(!ok(i,j)){ans = false; break;}
                }
            printf("%s\n",ans?"Yes":"No" );
        }
    }
    return 0;
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页