http://acm.hdu.edu.cn/showproblem.php?pid=5637
A list of nn integers are given. For an integer xx you can do the following operations:
+ let the binary representation of xx be b31b30...b0¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯b31b30...b0¯, you can flip one of the bits.
+ let yy be an integer in the list, you can change xx to x⊕yx⊕y, where ⊕⊕means bitwise exclusive or operation.
There are several integer pairs (S,T)(S,T). For each pair, you need to answer the minimum operations needed to change SS to TT.
Input
There are multiple test cases. The first line of input contains an integer TT (T≤20)(T≤20), indicating the number of test cases. For each test case:
The first line contains two integer nn and mm (1≤n≤15,1≤m≤105)(1≤n≤15,1≤m≤105)-- the number of integers given and the number of queries. The next line contains nn integers a1,a2,...,ana1,a2,...,an (1≤ai≤105)(1≤ai≤105), separated by a space.
In the next mm lines, each contains two integers sisi and titi (1≤si,ti≤105)(1≤si,ti≤105), denoting a query.
Output
For each test cases, output an integer S=(∑i=1mi⋅zi) mod (109+7)S=(∑i=1mi⋅zi) mod (109+7), where zizi is the answer for ii-th query.
Sample Input
1 3 3 1 2 3 3 4 1 2 3 9
Sample Output
10
Hint
$3 \to 4$ (2 operations): $3 \to 7 \to 4$ $1 \to 2$ (1 operation): $1 \oplus 3 = 2$ $3 \to 9$ (2 operations): $3 \to 1 \to 9$
给你一组数
然后询问s->t至少需要多少步
1.异或给定数
2.取反自己二进制上某一位
问题转化成0->s^t
至少需要多少步,用bfs预处理,然后回答即可
代码如下:
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<iostream>
#include<queue>
#include<map>
#include<bitset>
#include<algorithm>
using namespace std;
typedef long long LL;
const int INF = 0x7FFFFFFF;
const int mod = 1e9 + 7;
const int maxn = 1e5 + 4e4;
int T, n, m, ans;
int a[20], f[maxn], x, y;
bitset<20> t;
int main()
{
scanf("%d", &T);
while (T--)
{
scanf("%d%d", &n, &m); //这个数可以异或给定的一个数,也可以改变自己二进制位上的一个数;
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
memset(f, 1, sizeof(f));
queue<int> p; p.push(f[0] = 0);//开一个队列;
while (!p.empty())
{//广度优先搜索;
int q = p.front(); p.pop();
for (int i = 0; i < n; i++)
{
if (f[q^a[i]]>f[q] + 1)//如果它异或一个数大于本身加1的话(步数)
{
f[q^a[i]]=f[q] + 1;//q->q^a[i],这两个数之间有一步的距离;
p.push(q^a[i]);
}
}
for (int i = 0; i < 17; i++)
{
if (f[q^(1<<i)]>f[q] + 1)
{
f[q ^ (1 << i)] = f[q] + 1;//把某一位取反就相当与异或2的多少次方
p.push(q ^ (1 << i));
}
}//0异或任何数还是任何数;
}
int res = 0;
for (int k = 1; k <= m; k++)
{
scanf("%d%d", &x, &y);
(res += k*f[x^y]) %= mod;//这个题转化为0到X^Y需要多少步数,f数组记录步数;
}
printf("%d\n", res);
}
return 0;
}