hdu 2639

#include <stdio.h>
#define N 102
#define M 1002
int a[N], b[N], k, heap[M][31], hsize[M],c[33];
inline void merge(int a[], int an, int w, int b[], int &bn )
{
    int cn = 0, i=1, j=1, d=0;
    while( i<=an&&j<=bn&&d<k) if( a[i]+w == b[j] )i++;
        else if(a[i]+w>b[j]) c[++d]=a[i++]+w;
        else c[++d]=b[j++];
    while(i<=an&&d<k) c[++d]=a[i++]+w;
    while(j<=bn&&d<k) c[++d]=b[j++];
    for( i=1; i<=d; i ++ ) b[i]=c[i];
    bn=d;
}
int main()
{
    int cas, V, n, i, j,sum;
    scanf("%d",&cas);
    while( cas-- )
    {
        scanf("%d%d%d",&n,&V,&k);
        for(i=0; i<n; i++) scanf("%d",&a[i]);
        for(i=0; i<n; i++) scanf("%d",&b[i]);
        for(i=1; i<=V; i++ ) hsize[i] = 0;
        hsize[0]=1;
        heap[0][1]=sum=0 ;
        for(i=0; i<n; i ++  )
        {
            sum=b[i]+sum<V?b[i]+sum:V;
            for(j=sum; j >= b[i]; j -- )
            if( hsize[j-b[i]]>0 )
                merge(heap[j-b[i]],hsize[j-b[i]],a[i],heap[j],hsize[j]);
        }
        for(i=V-1;i>=1;i-- ) merge(heap[i],hsize[i],0,heap[V],hsize[V]);
        if(hsize[V]<k) puts("0");
        else printf("%d\n",heap[V][k]);
    }
    return 0;
}

堆實現

#include <stdio.h>
#define N 102
#define M 1002
int a[N], b[N], k, heap[M][31], hsize[M];
void keep_heap( int heap[], int s, int u )
{
    int x = u, l = u<<1, r = u<<1|1;
    if( l<=s && heap[x] > heap[l] ) x = l;
    if( r<=s && heap[x] > heap[r] ) x = r;
    if( x != u )
    {
        l = heap[x],heap[x]=heap[u],heap[u]=l;
        keep_heap(heap,s,x);
    }
}
void insert_heap( int heap[31], int &s, int x )
{
    if( s == k && x <= heap[1] ) return;
    for( int i = 1; i <= s; i ++ )
        if( x == heap[i] ) return ;
    if( s<k )
    {
        heap[++s] = x;
        for( int u = s; u>1 && heap[u]<heap[u/2]; u/=2 )
        x = heap[u], heap[u] = heap[u/2], heap[u/2] = x;
    }
    else if( s == k && heap[1]<x )
    {
        heap[1] = x;
        keep_heap(heap,s,1);
    }
}
int main()
{
    int cas, V, n, i, j,t,sum;
    scanf("%d",&cas);
    while( cas-- )
    {
        scanf("%d%d%d",&n,&V,&k);
        for(i=0; i<n; i++) scanf("%d",&a[i]);
        for(i=0; i<n; i++) scanf("%d",&b[i]);
        for(i=1; i<=V; i++ ) hsize[i] = 0;
        hsize[0]=1;
        heap[0][1]=sum=0 ;
        for(i = 0; i < n; i ++  )
        {
            sum=b[i]+sum<V?b[i]+sum:V;
            for(j=sum; j >= b[i]; j -- )
            if( hsize[j-b[i]]>0 )
                for(t = hsize[j-b[i]]; t>=1; t-- )
                insert_heap(heap[j],hsize[j],heap[j-b[i]][t]+a[i]);
        }
        for(i=V-1;i>=1;i-- )
        for(j=hsize[i];j>=1; j-- )
        insert_heap(heap[V],hsize[V],heap[i][j]);
        if(hsize[V]<k) puts("0");
        else printf("%d\n",heap[V][1]);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章