[USACO] weight

· · 个人记录

题目

        校内OJ。

分析

        首先不难想到暴力做法。
        枚举每个位子上面的数,时间O(N^{|S|})。
        然后发现这个东西无法优化......
        于是果断放弃该思路。由于a中的元素只会有两种情况——成为前缀或者成为后缀。所以这个东西其实就是在对这个a集合分成两个子集,大小都是N,并且还要满足前后缀和的性质。
        所以我们可以利用前后缀和来剪枝。
        设原数列为\{b_n\},S_i=\sum_{j=1}^i b_j,S'_i=\sum_{j=n-i+1}^n b_j。则我们不难发现如下性质:
        S_i-S_{i-1}=b_i,S'_i-S'_{i-1}=b_{n-i+1}。
        依靠这个来剪枝,再加上一个O(2^N)的搜索,我们就可把这道题骗过掉了。

代码

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>

const int MAXN = 1005, MAXM = 505, MAXSIZ = 500005;

template<typename _T>
void read( _T &x )
{
    x = 0;char s = getchar(); int f = 1;
    while( s < '0' || '9' < s ){ f = 1; if( s == '-' ) f = -1; s = getchar(); }
    while( '0' <= s && s <= '9' ){ x = ( x << 3 ) + ( x << 1 ) + s - '0', s = getchar(); }
    x *= f;
}

template<typename _T>
void write( _T x )
{
    if( x < 0 ){ putchar( '-' ), x = -x; }
    if( 9 < x ){ write( x / 10 ); }
    putchar( x % 10 + '0' );
}

int a[2 * MAXN], S[MAXM], cnt[MAXSIZ];
int seq[MAXN];
int N, M, tot;

bool chk()
{
    int tmp[MAXSIZ];
    memcpy( tmp, cnt, sizeof( cnt ) );
    int t1 = 0, t2 = 0;
    for( int i = 1 ; i <= N ; i ++ )
    {
        t1 += seq[i], t2 += seq[N - i + 1];
        if( ! tmp[t1] || ! tmp[t2] ) return false;
        tmp[t1] --, tmp[t2] --;
    }
    return true;
}

void DFS( const int indx, const int lps, const int rps, const int ls, const int rs )
{
    if( lps > rps )
    {
        if( chk() )
        {
            for( int i = 1 ; i <= N ; i ++ )
                write( seq[i] ), putchar( i == N ? '\n' : ' ' );
            exit( 0 );
        }
        return ;
    }
    if( indx > 2 * N ) return;
    for( int i = 1 ; i <= M ; i ++ )
        if( a[indx] - ls == S[i] )
        {
            seq[lps] = S[i];
            DFS( indx + 1, lps + 1, rps, ls + S[i], rs );
            break;
        }
    for( int i = 1 ; i <= M ; i ++ )
        if( a[indx] - rs == S[i] )
        {
            seq[rps] = S[i];
            DFS( indx + 1, lps, rps - 1, ls, rs + S[i] );
            break;
        }
}

int main()
{
    read( N );
    for( int i = 1 ; i <= N * 2 ; i ++ ) read( a[i] ), cnt[a[i]] ++;
    read( M );
    for( int i = 1 ; i <= M ; i ++ ) read( S[i] );
    std :: sort( a + 1, a + 1 + N * 2 );
    std :: sort( S + 1, S + 1 + M );
    seq[1] = a[1];
    DFS( 2, 2, N, a[1], 0 );
    return 0;
}