C++: Find the XOR of a closed interval of the array

I've worked out a solution, but it's not efficient. Could someone optimize my solution, using prefix sums.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;


int main() {
	int n, m;
	cin >> n >> m;
	int t[n];
	for(int i = 0; i < n; i++){
		cin >> t[i];
	}
	for(int i = 0; i < m; i++){
	    int a, b, aux = 0;
	    cin >> a >> b;
	    for(int j = a-1; j <= b-1; j++){
	        aux ^= t[j];
	    }
	    cout << aux << endl;
	}
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int main()
{
   int n, m;
   cin >> n >> m;
   
   int *t = new int[n];
   for ( int i = 0; i < n; i++ ) cin >> t[i];
   
   int *xort = new int[n];
   xort[0] = t[0];
   for ( int i = 1; i < n; i++ ) xort[i] = xort[i-1] ^ t[i];
   
   int a, b;
   while ( m-- )
   {
      cin >> a >> b;     // I'm guessing that a and b are one-based
      if ( a == 1 ) cout <<   xort[b-1]               << '\n';
      else          cout << ( xort[b-1] ^ xort[a-2] ) << '\n';
   }
   
   delete [] t;
   delete [] xort;
}
Topic archived. No new replies allowed.