[USACO] weight
题目
校内OJ。
分析
首先不难想到暴力做法。
枚举每个位子上面的数,时间
然后发现这个东西无法优化......
于是果断放弃该思路。由于
所以我们可以利用前后缀和来剪枝。
设原数列为
依靠这个来剪枝,再加上一个骗过掉了。
代码
#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;
}