UVALive - 4097: Yungom (greedy approach) (the DP)

pro: There D letters, each letter has its own weight, they need to spell out N status word, so that each of these words is not a prefix of another one. And the weight of words and minimal. D <= 200; N <= 200;

sol: If you create a trie, the value of each word right right value to the root path of redemption rights and leaf weight. Huffman feels a bit like a tree, but no big relationship, because they can not push down.

ND is relatively small since, we directly greedy, maintaining a size of the array b N + D [], has been updated, the following principles: every sort B [], the b [1] is replaced with b [1] + a [] ; has been operating, until no longer becomes small so far.

#include<bits/stdc++.h>
#define ll long long
#define rep(i,a,b) for(int i=a;i<=b;i++)
using namespace std;
const int maxn=410;
const ll inf=1LL<<45;
ll a[maxn],b[maxn];
int main()
{
    int N,D;ll ans;
    while(~scanf("%d%d",&N,&D)&&(N||D)){
        ans=0;
        rep(i,1,D) scanf("%lld",&a[i]);
        sort(a+1,a+D+1);
        rep(i,1,D) b[i]=a[i];
        rep(i,1,N)  b[i+D]=inf;
        rep(i,1,N) ans+=b[i];
        while(1){
            rep(i,1,D) b[i+N]=b[1]+a[i];
            b[1]=b[N+D];
            sort(b+1,b+N+D);
            ll sum=0;
            rep(i,1,N) sum+=b[i];
            if(sum<ans) ans=sum;
            else break;
        }
        printf("%lld\n",ans);
    }
    return 0;
}

 

Of course, also possible to do DP, DP [i] [j] denotes the i-th root has a son, when the minimum cost of the j-th leaf.

 

Guess you like

Origin www.cnblogs.com/hua-dong/p/10987800.html