HDU5637 BFS

http://acm.hdu.edu.cn/showproblem.php?pid=5637

//先bfs存储res值,查询时直接使用

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 n integers 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

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$

 

 

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define PI acos(-1.0)
#define E 1e-6
#define MOD 1000000007
#define INF 0x3f3f3f3f
#define N 300001
#define LL long long
using namespace std;
int a[N],res[N];
bool vis[N];
void bfs(int n){
    memset(vis,0,sizeof(vis));
    for(int i=1;i<=2e5;i*=2)//在给出的a[i]基础上向后补1、2、4、8...
        a[n++]=i;
 
    queue<int> Q;
    Q.push(0);
    res[0]=0;
    vis[0]=true;
    while(!Q.empty()){
        int top=Q.front();
        Q.pop();
 
        for(int i=0;i<n;i++){
            if(vis[a[i]^top]==false){
                Q.push(a[i]^top);//相应异或元素进队
                res[a[i]^top]=res[top]+1;//步数+1
                vis[a[i]^top]=true;//标记
            }
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        int n,m;
        scanf("%d%d",&n,&m);
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
 
        bfs(n);
        LL sum=0;
        int s,t;
        for(int i=1;i<=m;i++){
            scanf("%d%d",&s,&t);
            sum=(sum+(LL)i*res[s^t])%MOD;
        }
        printf("%d\n",(int)sum);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值