题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5637
Transform
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 901 Accepted Submission(s): 346
Problem Description
A list of n integers are given. For an integer x you can do the following operations:
+ let the binary representation of x be b31b30...b0¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯, you can flip one of the bits.
+ let y be an integer in the list, you can change x to x⊕y, where ⊕ means bitwise exclusive or operation.
There are several integer pairs (S,T). For each pair, you need to answer the minimum operations needed to change S to T.
Input
There are multiple test cases. The first line of input contains an integer T (T≤20), indicating the number of test cases. For each test case:
The first line contains two integer n and m (1≤n≤15,1≤m≤105) -- the number of integers given and the number of queries. The next line contains nintegers a1,a2,...,an (1≤ai≤105), separated by a space.
In the next m lines, each contains two integers si and ti (1≤si,ti≤105), denoting a query.
Output
For each test cases, output an integer S=(∑i=1mi⋅zi) mod (109+7), where zi is the answer for i-th query.
Sample Input
1
3 3
1 2 3
3 4
1 2
3 9
Sample Output
10
题目大意:
有两种变换:
1. 改变此数二进制的某一位(1变成0 或者 0变成1)
2. 让它与给出的n个数当中的任意一个做异或运算
给你两个数s, t,求从s到t最少要经过几步变换,一共m组查询
思路:
这道题目跟异或运算的性质有关;s^x^y^z^w^...^q=t;(中间的表示异或的步骤)
假设这是最少的流程,等价于0^x^y^z^w..^q=s^t;(因为0异或任何数都是他本身)
所以相当于0到s^t的最少次操作,然后设x=s^t,(x使用BFS求最短能够求出,然后t=x^s),相当于步数加一(可以初始化步数为1,就不用加1了
注意:需要预处理和输出的方式
This is the code
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<iomanip>
#include<list>
#include<map>
#include<queue>
#include<sstream>
#include<stack>
#include<string>
#include<set>
#include<vector>
using namespace std;
#define PI acos(-1.0)
#define EPS 1e-8
#define LL long long
#define ULL unsigned long long //1844674407370955161
#define INT_INF 0x7f7f7f7f //2139062143
#define LL_INF 0x7f7f7f7f7f7f7f7f //9187201950435737471
// ios::sync_with_stdio(false);
// 那么cin, 就不能跟C的 scanf,sscanf, getchar, fgets之类的一起使用了。
const int dr[]={0, 0, -1, 1, -1, -1, 1, 1};
const int dc[]={-1, 1, 0, 0, -1, 1, -1, 1};
const int mod=1e9+7;
int a[20];
int num[1<<17|5];
void bfs(int n)//类似于最短路预处理
{
memset(num,1,sizeof(num));
queue<int> q;
num[0]=0;
q.push(0);
while(!q.empty())
{
int t=q.front();
q.pop();
for(int i=0;i<n;++i)//异或给的数字
{
if(num[t^a[i]]>num[t]+1)
{
num[t^a[i]]=num[t]+1;
q.push(t^a[i]);
}
}
for(int i=0;i<17;++i)//0-1<<17的异或
{
if(num[t^(1<<i)]>num[t]+1)
{
num[t^(1<<i)]=num[t]+1;
q.push(t^(1<<i));
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,q;
scanf("%d%d",&n,&q);
for(int i=0;i<n;++i)
scanf("%d",a+i);
bfs(n);
int ans=0;
for(int i=1;i<=q;++i)
{
int s,t;
scanf("%d%d",&s,&t);
ans=(ans+i*num[s^t])%mod;//注意输出的要求
}
printf("%d\n",ans);
}
return 0;
}