51nod 2128 Prefix XOR

2128 prefix XOR

Subject link: http://www.51nod.com/Challenge/Problem.html#problemId=2128

Title description:

Enter an array of length n (1 <= n <= 100000) a[1], a[2], …, a[n].

Enter a query number m (1 <= m <= 100000) and m groups of queries, each group of queries has the form (l, r)

For each group of queries (l, r), you need to output a[l] xor a[l + 1] xor… xor a[r-1] xor a[r], which is the number from the lth digit to the rth digit XOR.

If your algorithm takes about n*m, you will only pass the first test point.

If your algorithm needs about n+m time, you will be able to pass this question.

enter:

The first line is an integer n and the
second line is n integers a[1], a[2],… a[n]. The
third line is an integer m
followed by m lines. Each line has two integers l and r for query.

Output:

A total of m lines are output, and an integer is output for each query to indicate the result.
Input example
3
1 2 3
6
1 1
2 2
3 3
1 2
2 3
1 3
Output example
1
2
3
3
1
0

Problem-solving ideas:

Prefix XOR , XOR of the same number twice is equal to itself, XOR from l to r, output a[r]^a[l-1].

code show as below:

#include<iostream>
#include<algorithm>
#include<cstdio>

using namespace std;

int main(){
    
    
	int n,m;
	int a[100005];
	cin>>n;
	for(int i=1;i<=n;i++){
    
    
		cin>>a[i];
		a[i]^=a[i-1];  //前缀异或
	}
	cin>>m;
	while(m--){
    
    
		int l,r;
		cin>>l>>r;
		printf("%d\n",a[r]^a[l-1]);  //l到r区间的异或,输出a[r]^a[l-1]
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45894701/article/details/115335517
Recommended