description
题目描述
长度为 n n n的序列,初始全为 0 0 0,每次可以选择⼀个数 a i ( 1 ≤ i ≤ l ) a_i(1\le i\le l) ai(1≤i≤l),然后选择连续 a i a_i ai个元素异或上 1 1 1
求最少的次数,使得对于所有 i ( 1 ≤ i ≤ k ) i(1\le i\le k) i(1≤i≤k)满足第 i i i个位置是 1 1 1,其他的位置都是 0 0 0
输入格式
第⼀行三个数 n , m , k n,m,k n,m,k
第二行 k k k个数分别表示 x 1 , x 2 , . . . , x k x_1,x_2,...,x_k x1,x2,...,xk
第三行 l l l个数分别表示 a 1 , a 2 , . . . a l a_1,a_2,...a_l a1,a2,...al
输出格式
一个数表示答案,若不能达到输出-1
样例
10 2 3
1 2
6 10 4
2
数据范围
n ≤ 10000 , k ≤ 10 , l ≤ 100 n\le 10000,k\le 10,l\le 100 n≤10000,k≤10,l≤100
solution
异或常见有两种处理
0-1
异或类,权值只有0
,1
显然某位异或偶数次相当于没操作,这就可以转化成差分
普通异或类
按二进制拆位做,每位答案是独立的
此题就是差分做法
e.g.
目标结果:1 0 0 1 1 0
,相邻两位权值不同就要差分出来
操作一段长为 a i a_i ai的段,就相当于在 p o s , p o s + a i pos,pos+a_i pos,pos+ai两个位置异或 1 1 1
本题 k k k范围极小,差分出来最多也就 20 20 20个位置
考虑从最后的状态用最少操作数变成全 0 0 0的初始状态
这相当于一张 n + 1 n+1 n+1点姻缘图,在差分 2 k 2k 2k个位置上有人,位置相差为 a i a_i ai的点对间有无向边,人沿着边移动,两人相遇牵手成功离开,求最少走过的边数,使得每个人都能找到自己的心动嘉宾
用bfs
处理出,每个人到达所有点走过的最少边数,到不了就置为inf
总人数不多,可以状压dp
枚举每次是哪两个人牵手成功,转移即可
code
#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define inf 0x3f3f3f3f
queue < pair < int, int > > q;
int n, k, l, cnt;
int dis[22][100002];
int x[100002], a[105], c[25];
int dp[1 << 22];
int dfs( int s ) {
if( ! s ) return 0;
if( dp[s] ^ inf ) return dp[s];
int &ans = dp[s], x = __builtin_ctz( s );
for( int y = cnt - 1;y > x;y -- )
if( 1 << y & s ) {
int t = dfs( s ^ ( 1 << y ) ^ ( 1 << x ) );
ans = min( ans, t + dis[x][c[y]] );
}
return ans;
}
int main() {
scanf( "%d %d %d", &n, &k, &l );
for( int i = 1, pos;i <= k;i ++ ) {
scanf( "%d", &pos );
x[-- pos] = 1;
}
for( int i = 1;i <= l;i ++ )
scanf( "%d", &a[i] );
if( x[0] ) c[cnt ++] = 0;
for( int i = 1;i <= n;i ++ )
if( x[i] ^ x[i - 1] ) c[cnt ++] = i;
if( cnt & 1 ) return ! printf( "-1" );
memset( dp, 0x3f, sizeof( dp ) );
memset( dis, 0x3f, sizeof( dis ) );
for( int i = 0, j, d, pos;i < cnt;i ++ ) {
dis[i][c[i]] = 0;
q.push( make_pair( 0, c[i] ) );
while( ! q.empty() ) {
d = q.front().first, pos = q.front().second; q.pop();
for( k = 1;k <= l;k ++ ) {
j = pos + a[k];
if( j <= n and dis[i][j] == inf )
dis[i][j] = d + 1, q.push( make_pair( d + 1, j ) );
j = pos - a[k];
if( j >= 0 and dis[i][j] == inf )
dis[i][j] = d + 1, q.push( make_pair( d + 1, j ) );
}
}
}
int ans = dfs( ( 1 << cnt ) - 1 );
printf( "%d\n", ans == inf ? -1 : ans );
return 0;
}