ACM Live Archive 4161 – Spherical Mirrors

Category : Geometry
Solution:
First we need to find the intersection between a sphere and a line.
a line is denoted by an origin and a direction vector.
a sphere is denoted a centre and radius. To find the intersection ,lets consider the equation of sphere.

Let p be a point on the sphere. Then the following equation holds
|p-c|^2 = r^2          ........... (1)
where c is the centre of the sphere and r is radius.

Now if the line intersects the sphere in point p, then we can write p as
p = o + d * x;
where o is origin of the line and d is direction unit vector of the line. x is the scaling factor.
putting p in equation (1)
|o+dx-c|^2 =r^2 \\  (dx).(dx) + 2*(dx).(o-c) + (o-c).(o-c) - r *r = 0
This is a quadratic equation of x in form ax^2 + bx + c = 0
where
a = d*d \\  b = 2 * (d.(o-c))\\  c = (o-c).(o-c) - r*r\\    discriminant = b * b - 4 * a * c;
if discriminant >= 0 , then the line intersects the sphere.
We can find x.
We will only take the value of x which is greater than ZERO (why ? )

After finding x , We can find the intersecting point.

Now we need to rotate the direction vector. This is shown in the following ways Reflection

/*
 *************************
 Id  : Matrix.code
 Task:
 Date: 2016-02-04

 **************************
 */


#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>

using namespace std;


/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define INF                     1<<29
#define EPS                     1e-12
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int> vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x){register int c = gc();x = 0;int neg = 0;for(;((c<48 | c>57) && c != '-');c = gc());
      if(c=='-') {neg=1;c=gc();}for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}if(neg) x=-x;}
Long bigmod(Long p,Long e,Long M){Long ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;} return ret;}
Long gcd(Long a,Long b){if(b==0)return a;return gcd(b,a%b);}
Long modinverse(Long a,Long M){return bigmod(a,M-2,M);}
void io(){freopen("/Users/MyMac/Desktop/in.txt","r",stdin);}

/*************************** END OF TEMPLATE ****************************/
#define Z(x)      (abs(x) < EPS)
#define ZN(x)     ( x < 0 || Z(x))
#define ZP(x)     ( x > 0 || Z(x))
const int N = 1005;
typedef double T;

struct PT{
      T x,y,z;
      PT(){}
      PT(T x,T y,T z):x(x),y(y),z(z){}
      void scan(){cin >> x >> y >> z;}
      PT operator + (const PT &p) const{ return PT(x+p.x,y+p.y,z+p.z);}
      PT operator - (const PT &p) const{ return PT(x-p.x,y-p.y,z-p.z);}
      PT operator * (const double c) const {return PT(x*c,y*c,z*c);}
      double abs(){ return sqrt(x*x+y*y+z*z);}
      void normal(){
            double d = this->abs();
            if(fabs(d) < EPS) return;
            x/=d;
            y/=d;
            z/=d;
      }
      void print() { printf("(%f %f %f)",x,y,z);}

};
double dot(PT a,PT b){ return a.x*b.x+a.y*b.y+a.z*b.z;}


struct Sp{
      PT cen;
      double rad;
      Sp(){}
};

vector<Sp> vs;
int main()
{
      //freopen("in.txt","r",stdin);
      int n;
      while(scanf("%d",&n)==1) {
            if(n==0) break;
            PT org(0,0,0);
            PT dir;
            dir.scan();
            dir.normal();
            Sp sp;
            for(int i= 0;i < n ;i ++) {
                  sp.cen.scan();
                  cin >> sp.rad;
                  vs.pb(sp);
            }

            PT ans;
            while(1) {
                  vector<pair<double,int> > Map;
                  for(int i= 0;i < n ;i ++) {
                        double a = dot(dir,dir);
                        double b = 2 * dot(dir, org - vs[i].cen);
                        double c = dot(org-vs[i].cen , org - vs[i].cen) - vs[i].rad * vs[i].rad;
                        double disc = b * b - 4 * a * c;
                        if(ZP(disc) ) {
                              double x1 = -b - sqrt(disc);
                              double x2 = -b + sqrt(disc);
                              x1/=(2*a); x2/=(2*a);
                              vector<double> k;
                              if(x1>EPS) k.pb(x1);
                              if(x2 > EPS) k.pb(x2);
                              sort(all(k));
                              if(k.size()) {
                                    Map.pb(mp(k[0],i));
                              }
                        }
                  }
                  if(Map.size() == 0 ) break;
                  sort(all(Map));
                  double x = Map[0].first;
                  double col = Map[0].second;
                  org = org + dir * x;
                  PT nor = org - vs[col].cen;nor.normal();
                  dir = dir - nor * 2 * dot(dir,nor);
                  ans = org;
                  Map.clear();

            }
            printf("%f %f %f\n",ans.x, ans.y,ans.z);
            vs.clear();
      }
      return 0;
}

Lightoj – 1130 – Intersection between Circle and Rectangle

Category : Geometry
Solution: Will be discussed Soon.

/*
 *************************
 Id  : Matrix.code
 Task: 1130 - Intersection between Circle and Rectangle
 Date: 2016-02-25

 **************************
 */


#include <bits/stdc++.h>
using namespace std;

/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define INF                     1<<29
#define EPS                     1e-9
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int > vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x){register int c = gc();x = 0;int neg = 0;for(;((c<48 | c>57) && c != '-');c = gc());
      if(c=='-') {neg=1;c=gc();}for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}if(neg) x=-x;}
Long bigmod(Long p,Long e,Long M){Long ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;} return ret;}
Long gcd(Long a,Long b){if(b==0)return a;return gcd(b,a%b);}
Long modinverse(Long a,Long M){return bigmod(a,M-2,M);}
void io(){freopen("/Users/MyMac/Desktop/in.txt","r",stdin);}

/*************************** END OF TEMPLATE ****************************/

const int N = 1001;

#define EPS		1e-12
#define _abs(x)		(((x)>0)?(x):-(x))
#define _max(x,y)	(((x)>(y))?(x):(y))
#define _min(x,y)	(((x)<(y))?(x):(y))

#define E(x,y)	(_abs((x)-(y)) < EPS)
#define Z(x)	(_abs(x) < EPS)
#define ZN(x)	(x < 0 || Z(x))
#define ZP(x)	(x > 0 || Z(x))
#define S(x)	((x)*(x))

#define UNDEF	-1
#define OUTSIDE	0
#define INSIDE	1
#define CUT     2
//0 <= x1 <= x2 <= R
double ySlice(double R,double x1,double x2){		// area bounded by y=0, x=x1, x=x2, y = sqrt(R*R - x*x)
	double a,t1,t2;

	assert( ZP(x1) );
	assert( ZP(x2-x1) );
	assert( ZP(R-x2) );

	t2 = acos(x2/R);
	t1 = acos(x1/R);
	a  = 0.5*( S(R)*(t1-t2) + R*(x2*sin(t2) - x1*sin(t1)) );

	assert( ZP(a) );

	return a;
}

//rect(x1,x2,y1,y2) must be in the FIRST quadrant, 0<=x1<=x2, 0<=y1<=y2
double posXYRectCommon(double R,double x1,double x2,double y1,double y2,int &flag){
	double x3,x4,a,d11,d12,d21,d22;

	assert( ZP(x1));
	assert( ZP(y1));
	assert( ZP(x2-x1) );
	assert( ZP(y2-y1) );

	d11 = S(x1)+S(y1) - S(R);
	d12 = S(x1)+S(y2) - S(R);
	d21 = S(x2)+S(y1) - S(R);
	d22 = S(x2)+S(y2) - S(R);

	if( ZN(d22) ){					//case 1
		a  = (x2-x1)*(y2-y1);
		flag = _max(flag,INSIDE);
	}
	else if( ZN(d12) && ZN(d21) ){	//case 2
		x3 = sqrt(S(R) - S(y2));	//x3 <= x2
		a  = (x3-x1)*(y2-y1) + ySlice(R,x3,x2) - (x2-x3)*y1;
		flag = _max(flag,CUT);
		assert(ZP(x2-x3));
	}
	else if( ZN(d12) ){				//case 3
		x3 = sqrt(S(R) - S(y2));	//x3 <= x4
		x4 = sqrt(S(R) - S(y1));
		a  = (x3-x1)*(y2-y1) + ySlice(R,x3,x4) - (x4-x3)*y1;
		flag = _max(flag,CUT);
		assert(ZP(x4-x3));
	}
	else if( ZN(d21) ){				//case 4
		a  = ySlice(R,x1,x2) - (x2-x1)*y1;
		flag = _max(flag,CUT);
	}
	else if( ZN(d11) ){				//case 5
		x3 = sqrt(S(R) - S(y1));	//x1 <= x3
		a  = ySlice(R,x1,x3) - (x3-x1)*y1;
		flag = _max(flag,CUT);
		assert(ZP(x3-x1));
	}
	else{							//case 6
		a = 0;
		flag = _max(flag,OUTSIDE);
	}

	assert( ZP(a) );
	assert( ZP( (x2-x1)*(y2-y1) - a) );

	return a;
}

double XYRectCommon(double x,double y,double R,double x1,double x2,double y1,double y2,int &flag){
	double a;
	x1-=x;
	x2-=x;
	y1-=y;
	y2-=y;

	flag = UNDEF;

	if(ZP(x1) && ZP(y1)){
		a = posXYRectCommon(R,x1,x2,y1,y2,flag);
	}
	else if(ZP(x1)){		//y1 < 0
            if(ZN(y2)) a = posXYRectCommon(R,x1,x2,-y2,-y1,flag);
            else {
                  a = posXYRectCommon(R,x1,x2,0, y2,flag);
                  a+= posXYRectCommon(R,x1,x2,0,-y1,flag);
            }

	}
	else if(ZP(y1)){		//x1 < 0
            if(ZN(x2)) {
                  a = posXYRectCommon(R,-x2,-x1,y1,y2,flag);
            }else {
		a = posXYRectCommon(R,0, x2,y1,y2,flag);
		a+= posXYRectCommon(R,0,-x1,y1,y2,flag);
            }
	}
	else{			//x1 < 0 && y1 < 0
            if(ZN(x2) &&ZN(y2)) a = posXYRectCommon(R,-x2,-x1,-y2,-y1,flag);
		else if(ZN(y2)) a = XYRectCommon(0,0,R,x1,x2,-y2,-y1,flag);
		else if(ZN(x2)) a = XYRectCommon(0,0,R,-x2,-x1,y1,y2,flag);
		else {
                  a = posXYRectCommon(R,0, x2,0, y2,flag);
                  a+= posXYRectCommon(R,0, x2,0,-y1,flag);
                  a+= posXYRectCommon(R,0,-x1,0, y2,flag);
                  a+= posXYRectCommon(R,0,-x1,0,-y1,flag);
		}
	}
	return a;
}

int main(){

      //freopen("in.txt","r",stdin);
	int flag;
	double x,y,R,x1,x2,y1,y2;
      Di(t);
      int cs = 0;
      while(t--) {
            scanf("%lf%lf%lf%lf%lf%lf%lf",&x,&y,&R,&x1,&y1,&x2,&y2);
		printf("Case %d: %.10f\n",++cs,XYRectCommon(x,y,R,x1,x2,y1,y2,flag));
      }


	return 0;
}



Fast Multiplication

Category : FFT
Problem Link : HDU 1402

Solution :

/*
 *************************
 Id  : Matrix.code
 Task:
 Date: 2016-03-05

 **************************
 */


#include <bits/stdc++.h>
using namespace std;
/*
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
*/
#define Long                    long long
#define Ulong                   unsigned long long
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define EPS                     1e-9
#define F                       first
#define S                       second
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define si(a)                   scanf("%d",&a);
#define sii(a,b)                si(a);si(b)
#define siii(a,b,c)             si(a);si(b);si(c)
#define sl(a)                   scanf("%lld",&a)
#define sll(a,b)                sl(a);sl(b)
#define slll(a,b,c)             sl(a);sll(b,c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
#define ms(ara_name,value)      memset(ara_name,value,sizeof(ara_name))
#define show(x)                 {for(auto ii: x) cout << ii <<" "; puts("");}
/*************************** END OF TEMPLATE ****************************/

typedef complex<double> Complex;
void fft(vector<Complex> & a, bool inv) {
	int n = (int)a.size();

	for (int i = 1, j = 0; i<n; ++i) {
		int bit = n >> 1;
		for (; j >= bit; bit >>= 1)
			j -= bit;
		j += bit;
		if (i < j)
			swap(a[i], a[j]);
	}

	for (int len = 2; len <= n; len <<= 1) {
		double ang = 2 * PI / len * (inv ? -1 : 1);
		Complex wlen(cos(ang), sin(ang));
		for (int i = 0; i<n; i += len) {
			Complex w(1);
			for (int j = 0; j<len / 2; ++j) {
				Complex u = a[i + j], v = a[i + j + len / 2] * w;
				a[i + j] = u + v;
				a[i + j + len / 2] = u - v;
				w *= wlen;
			}
		}
	}
	if (inv)
	for (int i = 0; i<n; ++i)
		a[i] /= n;

}

vector<int> mult(vector<int>& a, vector<int>& b) {

	vector<Complex> fa(a.begin(), a.end()), fb(b.begin(), b.end());
	size_t n = 1;
	while (n < max(a.size(), b.size()))  n <<= 1;
	n <<= 1;
	fa.resize(n), fb.resize(n);

	fft(fa, false), fft(fb, false);
	for (size_t i = 0; i<n; ++i)
		fa[i] *= fb[i];
	fft(fa, true);

	vector<int> res;
	res.resize(n);
	for (size_t i = 0; i<n; ++i)
		res[i] = int(fa[i].real() + 0.5);
	return res;
}

const int N = 50005;

char a[N],b[N];
vector<int> A,B;
int main()
{
      while(scanf("%s %s",a,b)==2) {
            int lenA = strlen(a), lenB= strlen(b);
            A.clear();
            B.clear();
            for(int i= lenA-1; i>=0; i--) A.push_back(a[i]-'0');
            for(int i =lenB-1; i>=0 ;i--) B.push_back(b[i]-'0');
            vector<int> res= mult(A,B);
            int carry = 0;
            for(int i= 0;i < res.size();i ++) {
                  int k = res[i] + carry;
                  res[i] = k%10;
                  carry = k/10;
            }
            if(carry) res.pb(carry);

            bool flag = 0;
            for(int i = res.size()- 1; i>=0; i--) {
                  if(res[i])flag=1;
                  if(flag) printf("%d",res[i]);
            }
            if(!flag) printf("0");
            puts("");
      }
      return 0;
}

Geometry Funs

Category : Geometry, Convex Hull
Problem Link : Biathlon 2.0
Short Description :
Given n pair of integer(a,b). Also given m pair of integer (x,y).
For each n pair , output the min( a * xi + b * yi) where 1<=i<=m

Solution:

    First build the convex hull of m pair of interger as point. As the point inside the convex hull can not give minimum value for a given point. Because the same value can be obtained from the point lying in the convex hull.
    Ternary search on the point of the convex hull. Find the minimum

/*
 *************************
 Id  : Matrix.code
 Task: H. Biathlon 2.0
 Date: 2016-02-14

 **************************
 */


#include <bits/stdc++.h>
using namespace std;

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;


/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define INF                     1e18
#define EPS                     1e-2
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int > vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x){register int c = gc();x = 0;int neg = 0;for(;((c<48 | c>57) && c != '-');c = gc());
      if(c=='-') {neg=1;c=gc();}for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}if(neg) x=-x;}
Long bigmod(Long p,Long e,Long M){Long ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;} return ret;}
Long gcd(Long a,Long b){if(b==0)return a;return gcd(b,a%b);}
Long modinverse(Long a,Long M){return bigmod(a,M-2,M);}
void io(){freopen("/Users/MyMac/Desktop/in.txt","r",stdin);}

/*************************** END OF TEMPLATE ****************************/

const int N = 5e5+5;

Long  x[N],y[N],c[N],d[N];

struct PT{
      double x,y;
      PT operator + (const PT &q) {return {x+q.x,y+q.y};}
      PT operator - (const PT &q) {return {x-q.x,y-q.y};}
      PT operator * (double c   ) {return {x*c,y*c};    }
      PT operator / (double c  ) {return {x/c,y/c};}
}P[N];
double sqr(double a){return a*a;}
double dist2(PT a, PT b) {return sqr(a.x-b.x) + sqr(a.y-b.y);}
double dot(PT a,PT b) {return a.x*b.x+a.y*b.y;}
double cross(PT a,PT b){return a.x*b.y-a.y*b.x;}
double DIM(PT a) {return sqrt(a.x*a.x+a.y*a.y);}


PT pivot;
bool cmp(PT a, PT b)
{
      double d = cross(a-pivot,b-pivot);
      if(d>0) return 1;
      else if(d<0)return 0;
      else {
            double d1 = dist2(pivot,a);
            double d2 = dist2(pivot,b);
            return d1<d2;
      }
}
vector<PT> Hul, H;

void CH(vector<PT> &P , int SZ)
{
      double iy = INF ;
      int id = -1;
      for(int i= 0;i < SZ; i ++ ) {
            if(P[i].y < iy){
                  iy = P[i].y, id = i;
            }
      }
      swap(P[0],P[id]);
      pivot = P[0];

      sort(all(P), cmp);
      Hul.pb(P[0]);
      Hul.pb(P[1]);
      for(int i = 2;i < SZ ; i++ ) {
            while(Hul.size() > 1 && cross(Hul[Hul.size() - 1] - Hul[Hul.size() -2 ] , P[i] - Hul[Hul.size()-1] ) < 0 ) Hul.pop_back();
            Hul.pb(P[i]);
      }


}
vector<PT> pp;



int main()
{
      //freopen("in.txt","r",stdin);
      int n;
      scanf("%d",&n);
      for(int i = 0; i < n ;i ++ ) {
            Sii(x[i],y[i]);
      }
      int m;
      Si(m);
      for(int i = 0; i < m ;i ++ ) {
            Sii(c[i],d[i]);
            pp.push_back({c[i], d[i]});
      }
      pp.push_back({INF,INF});

      CH(pp,pp.size());


      for(int i = 0;i < SZ(Hul); i ++ ) {
            if(fabs(Hul[i].x - INF) < EPS) {
                  for(int j= i + 1 ; j < SZ(Hul) ; j ++ ) H.pb(Hul[j]);
                  for(int j= 0; j < i; j ++ ) H.pb(Hul[j]);
                  break;
            }
      }

      for(int i = 0; i < n; i ++ ) {
            int x1 = x[i], y1 = y[i];
            Long low = 0, high = H.size()-1, ans= 4e18;

            while(low <= high ) {
                  Long f = low + (high - low ) /3;
                  Long g = high- (high - low) / 3 ;
                  Long ff = x1*H[f].x + y1 *H[f].y;
                  Long fg = x1*H[g].x + y1 *H[g].y;

                  if(ff < fg) {
                        ans = min(ans, ff);
                        high = g-1;
                  }else {
                        ans = min(ans, fg);
                        low = f+1;
                  }
            }
            printf("%lld ", ans);
      }

      return 0;

}

lightoj 1120 – Rectangle Union

#include <bits/stdc++.h>
using namespace std;


/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define INF                     1<<29
#define EPS                     1e-9
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int > vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x){register int c = gc();x = 0;int neg = 0;for(;((c<48 | c>57) && c != '-');c = gc());
      if(c=='-') {neg=1;c=gc();}for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}if(neg) x=-x;}
Long bigmod(Long p,Long e,Long M){Long ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;} return ret;}
Long gcd(Long a,Long b){if(b==0)return a;return gcd(b,a%b);}
Long modinverse(Long a,Long M){return bigmod(a,M-2,M);}
void io(){freopen("/Users/MyMac/Desktop/in.txt","r",stdin);}

/*************************** END OF TEMPLATE ****************************/

const int N = 1e5+5;

struct Edge{
      int x,y1,y2;
      int type ;
      Edge(){}
      Edge(int x,int y1,int y2,int type):x(x),y1(y1),y2(y2), type(type) {}
      bool operator < (const Edge &e) const {
            return x < e.x;
      }
};
vector<Edge> edge;
vector<int>v;
int lazy[4*N],seg[4*N];
int update(int n,int b,int e,int i,int j,int t)
{

      if(b>j || e<i) {
            if(lazy[n]) return v[e+1] - v[b];
            else return seg[n];
      }
      if(b>=i && e<=j) {
            lazy[n] += t;
            if(lazy[n]) return v[e+1] - v[b];
            else return seg[n];
      }
      int mid = (b+e)/2;
      int k1 = update(lc,b,mid,i,j,t);
      int k2 = update(rc,mid+1,e,i,j,t);
       seg[n] = k1+k2;
       
       if(lazy[n]) return v[e+1] - v[b];
       else return seg[n];
}

int main()
{
      //freopen("in.txt","r",stdin);
      Di(t);
      int cs = 0;
      while(t--) {
            Di(n);
            Edge e;
            for(int i= 0; i < n; i ++ ) {
                  Dii(x1,y1);
                  Dii(x2,y2);
                  v.pb(y1);
                  v.pb(y2);
                  e.x = x1;
                  e.y1 = y1;
                  e.y2 = y2;
                  e.type = 1;
                  edge.pb(e);
                  e.x = x2;
                  e.type = -1;
                  edge.pb(e);
            }
            sort(all(v));
            v.resize(unique(all(v)) - v.begin());
            sort(all(edge));

            for(int i= 0;i < edge.size();i ++ ) {
                  edge[i].y1 = lower_bound(all(v),edge[i].y1) - v.begin();
                  edge[i].y2 = lower_bound(all(v),edge[i].y2) - v.begin() - 1;
            }
            int nn = v.size();
            Long len = update(1,0,nn-1, edge[0].y1 , edge[0].y2 , 1);
            Long prv =  edge[0].x;
            Long ans = 0;
            for(int i = 1;i < edge.size() ; i ++ ) {

                  ans += len * (edge[i].x - prv) ;
                  len = update(1,0,nn-1,edge[i].y1,edge[i].y2,edge[i].type);
                  prv = edge[i].x;
            }
            printf("Case %d: %lld\n", ++cs, ans);
            v.clear();
            edge.clear();
      }
      return 0;

}

POJ – 3274

Category : Hashing
Solution :
Will be explained later.

/*
 *************************
 Id  : Matrix.code
 Task: POJ - 3274
 Date: 2016-02-10

 **************************
 */
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <map>
using namespace std;

/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define INF                     1<<29
#define EPS                     1e-9
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int > vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x)
{
    register int c = gc();
    x = 0;
    int neg = 0;
    for(; ((c<48 | c>57) && c != '-'); c = gc());
    if(c=='-')
    {
        neg=1;
        c=gc();
    }
    for(; c>47 && c<58; c = gc())
    {
        x = (x<<1) + (x<<3) + c - 48;
    }
    if(neg) x=-x;
}
Long bigmod(Long p,Long e,Long M)
{
    Long ret = 1;
    for(; e > 0; e >>= 1)
    {
        if(e & 1) ret = (ret * p) % M;
        p = (p * p) % M;
    }
    return ret;
}
Long gcd(Long a,Long b)
{
    if(b==0)return a;
    return gcd(b,a%b);
}
Long modinverse(Long a,Long M)
{
    return bigmod(a,M-2,M);
}
void io()
{
    freopen("/Users/MyMac/Desktop/in.txt","r",stdin);
}

/*************************** END OF TEMPLATE ****************************/

const int N = 100005;
int a[N];
int pf[31][N];
map<pair<Long,Long> ,int>Map;
int n,k;
Long MOD1 = 1e9+7;
Long MOD2 = 1e9+9;
Long base = 31;
Long base2= 37;
pair<Long,Long> H(int a[],int k)
{
    Long ret1 = 0, ret2 = 0;

    for(int i= 0; i < k - 1 ; i ++ ) {
            ret1 = ret1 * base + a[i];
            ret2 = ret2 * base2 + a[i];
            ret1 %=MOD1;
            ret2 %= MOD2;
    }

    return mp(ret1,ret2);
}

int main()
{

      //freopen("in.txt","r",stdin);

    scanf("%d %d ",&n,&k);
    for(int i= 1; i <= n; i ++ )
    {
        scanf("%d",&a[i]);
    }
    if(k==1)
    {
        printf("%d\n",n);
        return 0;
    }
    for(int i= 1; i <= n; i ++ )
    {
        for(int j = 0 ; j < k ; j ++ )
        {
            if(a[i] & (1<<j))
            {
                pf[j][i] = pf[j][i-1] + 1;
            }
            else pf[j][i] = pf[j][i-1];
        }
    }
    int iM = 0;
    int t[35];
    Map[mp(0,0)] = 0;
    for(int i= 1; i <= n; i ++ )
    {
        for(int j = 1; j < k ; j ++ )
        {
            t[j-1] = pf[j][i]- pf[j-1][i];

        }

        pair<Long,Long> k1 = H(t,k);

        if(Map.count(k1))
        {
            iM = max(iM, i - Map[k1]);
        }
        else Map[k1] = i;
    }
    cout << iM << endl;
}

HDU – 3032

Category : Game Theory
Link : Problem

Solution :
The problem requires knowledge about nim game and Sprague–Grundy theorem. If you don’t know this, then game : topcoder
can help.

So proceed to solution, As each heap is independent, So this game is combination of games, and there we can apply grundy number.
We will find grundy number for each heap. If there are n heap, we calculate grundy number of each heap and xor them. If xorsum NONZERO, first one wins, othewise second person to move wins.

The only problem is to find grundy number of each pile.

Starting with 0 : grundy number gr(0) = 0, because it is a losing position.

When p = 1
we can move to only one position (0) , as 0 has grundy value of 0, then gr(1) = 1;

1

When p = 2
we can move to 0, 1, (1,1)(Spliting into 2 heap).

2
So

gr(2) = 2

When p = 3 we can move to 0, 1, 2,(1,2)(Spliting into 2 heap).

3
Here grundy value of the state (1,2) = 3 because gr(1) ^ gr(2) = 1 ^ 2 = 3;
so

gr(3) = 4

When p = 4

4
Here

gr(4) = 3

If we try like this we will find a pattern and this is

      if(n==0) return 0;
      if(n%4==1 || n%4 == 2) return n ;
      if(n%4 == 3) return n + 1;
      if(n%4 == 0) return n - 1;

So the solution is now obvious.

My code :

/*
 *************************
 Id  : Matrix.code
 Task: HDU - 3032
 Date: 2016-02-10

 **************************
 */


#include <bits/stdc++.h>
using namespace std;

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;


/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define INF                     1<<29
#define EPS                     1e-9
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int > vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x){register int c = gc();x = 0;int neg = 0;for(;((c<48 | c>57) && c != '-');c = gc());
      if(c=='-') {neg=1;c=gc();}for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}if(neg) x=-x;}
Long bigmod(Long p,Long e,Long M){Long ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;} return ret;}
Long gcd(Long a,Long b){if(b==0)return a;return gcd(b,a%b);}
Long modinverse(Long a,Long M){return bigmod(a,M-2,M);}
void io(){freopen("/Users/MyMac/Desktop/in.txt","r",stdin);}

/*************************** END OF TEMPLATE ****************************/

const int N = 1001;

int gr(int n)
{
      if(n==0) return 0;
      if(n%4==1 || n%4 == 2) return n ;
      if(n%4 == 3) return n + 1;
      if(n%4 == 0) return n - 1;
}


int main()
{
      //freopen("in.txt","r",stdin);
      Di(t);
      while(t--) {
            Di(n);
            int ans = 0;
            for(int i = 0;i  < n; i ++ ) {
                  Di(a);
                  ans ^= gr(a);
            }
            printf("%s\n", ans ? "Alice" : "Bob");
      }
      return 0;

}

HDU – 4609 – 3-idiots

Category : FFT
Problem:
Given n(10^5) sticks.Picking 3 sticks from there. What is the probability so that it forms a triangle.

Solution:
Notations:

a[] -> The length of the sticks are stored
cnt[] -> cnt[i] denotes how many time length i occur

Let a[]= {1,2,3,3}
From this array picking two different integer, what length can we make?

1+2=3, 
1+3=4,
1+3=4
2+3=5, 
2+3=5,
3+3=6,

So We can represent them taking the occurance of the numbers. as follows

Table 1


0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
0 | 0 | 0 | 1 | 2 | 2 | 1 | 0 | 0

Now How to use FFT ?
Okay make polynomial of cnt[] array.
Thus,
E = 2*x^3 + x^2  + x ;\\  E * E = E^2 = 4x^6 + 4x^5 + 5x^4 + 2x^3 +x^2
The representation of this :

Table 2

0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
0 | 0 | 1 | 2 | 5 | 4 | 4 | 0 | 0

You can guess how we find E^2, now can we find the prevous from this ?
{1,2,3,3} * {1,2,3,3}
By picking one from first and one from other,

1+1=2;
1+2=3;
1+3=4;
1+3=4;
2+1=3;
2+2=4;
2+3=5;
2+3=5;
3+1=4;
3+2=5;
3+3=6
3+3=6;
3+1=4;
3+2=5;
3+3=6
3+3=6;

So we represent this to array, it would look like the mentioned.
Now how to transform so that it generates table 1:
Note : For table 2,

    a interger is adding to itself
    1 + 2, 2+1, generates 2 but in table 1, it was generating 1, as permutation does not matter.

Using this above condition we can Transform 2 to Table 1
So, # minus num[a[i]*2] –, for every i
# divide each by 2 , num[i]/=2;

Now we have the Table 1 array.
How do we find the desired answer ?
sort the whole array,then take each length to be longest length of the triangle, So the summation of other sticks should be greater than this one.
details in code comment.

/*
 *************************
 Id  : Matrix.code
 Task: HDU - 4609
 Date: 2016-02-07

 **************************
 */


#include <bits/stdc++.h>
using namespace std;

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;


/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define INF                     1<<29
#define EPS                     1e-9
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int > vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x){register int c = gc();x = 0;int neg = 0;for(;((c<48 | c>57) && c != '-');c = gc());
      if(c=='-') {neg=1;c=gc();}for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}if(neg) x=-x;}
Long bigmod(Long p,Long e,Long M){Long ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;} return ret;}
Long gcd(Long a,Long b){if(b==0)return a;return gcd(b,a%b);}
Long modinverse(Long a,Long M){return bigmod(a,M-2,M);}
void io(){freopen("/Users/MyMac/Desktop/in.txt","r",stdin);}

/*************************** END OF TEMPLATE ****************************/

const int N = 1<<18;

typedef long double T;
long double PI = acos(-1.0); // Without long double gives WA
struct Complex{
      T x,y;
      Complex(T x=0,T y=0):x(x),y(y){}
      Complex operator + (const Complex &a) const{return Complex(x+a.x,y+a.y);};
      Complex operator - (const Complex &a) const{return Complex(x-a.x,y-a.y);};
      Complex operator * (const Complex &a) const{return Complex(x*a.x-y*a.y,x*a.y+y*a.x);};
};

struct Fast_Fourier{
      Complex A[1 << 18];
      int rev(int id, int len)
      { // Reversed bit value , 011 -> 110
            int ret = 0;
            for(int i = 0; (1 << i) < len; i++){
                  ret <<= 1;
                  if(id & (1 << i)) ret |= 1;
            }
            return ret;
      }


      void FFT(Complex a[], int len, int DFT)
      {
            for(int i = 0; i < len; i++) A[rev(i, len)] = a[i];
            for(int s = 1; (1 << s) <= len; s++)
            {
                  int m = (1 << s);
                  Complex wm = Complex(cos(DFT*2*PI/m), sin(DFT*2*PI/m));
                  for(int k = 0; k < len; k += m)
                  {
                        Complex w = Complex(1, 0);
                        for(int j = 0; j < (m >> 1); j++)
                        {
                              Complex t = w*A[k + j + (m >> 1)];
                              Complex u = A[k + j];
                              A[k + j] = u + t;
                              A[k + j + (m >> 1)] = u - t;
                              w = w*wm;
                        }
                  }
            }
            if(DFT == -1) for(int i = 0; i < len; i++) A[i].x /= len, A[i].y /= len;
            for(int i = 0; i < len; i++) a[i] = A[i];
            return;
      }

}fft ;
Complex x[1<<18];
Long num[1<<18];
int a[N];
int cnt[N];
Long sum[N];
int main()
{
     // freopen("in.txt","r",stdin);
      Di(t);
      while(t--) {
            Long n;
            Si(n);
            int iM = 0;
            for(int i= 0;i < n;i ++) {
                  Si(a[i]);
                  cnt[a[i]] ++;
                  iM = max(iM , a[i]);
            }
            sort(a,a+n);
            int len = 1;
            while(len <= 2 * iM) len *= 2;
            for(int i= 0;i < len;i ++) {
                  x[i] = Complex(cnt[i],0);
            }
            fft.FFT(x,len,1);
            for(int i= 0;i < len;i ++) {
                  x[i] = x[i] * x[i];
            }
            fft.FFT(x,len,-1);
            for(int i= 0;i < len;i ++) {
                  num[i] = (Long)(x[i].x + .5 );
            }
            for(int i= 0; i < n; i ++) {
                  num[a[i] + a[i]] --;
            }
            for(int i= 0;i < len;i ++) {
                  num[i]/=2;
            }
            // prefix sum
            for(int i= 1;i < len; i ++) {
                  sum[i] = num[i] + sum[i-1];
            }
            Long ans = 0;
            for(int i= 0 ;i < n; i++ ) {
                  ans += sum[len-1] - sum[a[i]]; // # of ways such that summation of length > a[i]
                  ans -= (n-1-i) * i; // as a[i], is the largest,so there are (n-1-i) are bigger than a[i]. They with any number less tham a[i] is included in first case. So substract them.
                  ans -= (n-1); 
                  ans -= (n-i-1) * (n-i-2) / 2; // number of ways where the both length > a[i] , subtract them.
            }
            Long tot = ((Long)n ) * (n-1) * (n-2)/6;
            printf("%.7lf\n", ans*1./ tot);
            ms(cnt,0);


      }
      return 0;

}

Xor-sequence

Problem Link : Xor – Sequence
Solution :

From the Hacker Rank editorial:
Let’s have a look at array A:

A1=1
A2=1⊕2
A3=1⊕2⊕3
A4=1⊕2⊕3⊕4
A5=1⊕2⊕3⊕4⊕5

Now, let’s make array B where Bi=A0⊕A1⊕A2⊕…⊕Ai.
Bi=A0⊕A1⊕A2⊕…⊕Ai−1⊕Ai=Bj⊕Aj+1⊕Aj+2⊕…⊕Ai. For any 0≤j<i.
So AL⊕AL+1⊕…⊕AR=BL−1⊕BR.

Now, let's have a look at array B:

B1=1
B2=2
B3=1⊕3
B4=2⊕4
B5=1⊕3⊕5
B6=2⊕4⊕6
B7=1⊕3⊕5⊕7
B8=2⊕4⊕6⊕8

It’s easy to observe that in odd indexes Bi=1⊕3⊕5⊕…⊕i
and for even indexes Bi=2⊕4⊕6⊕…⊕i

for even indexes there are numbers from 1 to i/2 multiplied by 2, that means bit’s are moved to left by 1, so, Bi=2⊕4⊕6⊕…⊕i=(1⊕2⊕3⊕…⊕i/2)∗2.
And for odd indexes there are numbers from 0 to (i−1)/2 multiplied by 2 and plus 1. That means bit’s are moved to left by 1, and last bit is made 1. so, Bi=1⊕3⊕5⊕…⊕i=(0⊕1⊕2⊕…⊕(i−1)/2)∗2+X.
X is 1⊕1⊕1⊕..⊕1 “ones” are repeated (i−1)/2+1 times. So, if (i−1)/2+1 is odd then X=1 else X=0.

Now, calculation of 1⊕2⊕3⊕…⊕x.
Let’s prove that (4K)⊕(4K+1)⊕(4K+2)⊕(4K+3)=0 for 0≤K.

My code:

/*
 *************************
 Id  : Matrix.code
 Task: Xor-sequence
 Date: 2016-02-01

 **************************
 */


#include <bits/stdc++.h>
using namespace std;

#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;


/*------- Constants---- */

#define Long                    long long
#define ull                     unsigned long long
#define mod                     1000000007
#define MEMSET_INF              63
#define MEM_VAL                 1061109567
#define forn(i,n)               for( int i=0 ; i < n ; i++ )
#define mp(i,j)                 make_pair(i,j)
#define lop(i,a,b)              for( int i = (a) ; i < (b) ; i++)
#define pb(a)                   push_back((a))
#define SZ(a)                   (int) a.size()
#define all(x)                  (x).begin(),(x).end()
#define gc                      getchar_unlocked
#define PI                      acos(-1.0)
#define INF                     1<<29
#define EPS                     1e-9
#define Fr                      first
#define Sc                      second
#define Sz                      size()
#define lc                      ((n)<<1)
#define rc                      ((n)<<1|1)
#define db(x)                   cout << #x << " -> " << x << endl;
#define Di(n)                   int n;si(n)
#define Dii(a,b)                int a,b;si(a);si(b)
#define Diii(a,b,c)             int a,b,c;si(a);si(b);si(c)
#define Si(n)                   si(n)
#define Sii(a,b)                si(a);si(b)
#define Siii(a,b,c)             si(a);si(b);si(c)
#define min(a,b)                ((a)>(b) ? (b) : (a) )
#define max(a,b)                ((a)>(b) ? (a):(b))
/*---- short Cuts ------- */
#define ms(ara_name,value) memset(ara_name,value,sizeof(ara_name))
typedef pair<int, int> ii;
typedef vector<int > vi ;
typedef vector<Long> vl;
/*------ template functions ------ */
#ifndef getchar_unlocked
#define getchar_unlocked getchar
#endif
template<class T> inline void si(T &x){register int c = gc();x = 0;int neg = 0;for(;((c<48 | c>57) && c != '-');c = gc());
      if(c=='-') {neg=1;c=gc();}for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}if(neg) x=-x;}
Long bigmod(Long p,Long e,Long M){Long ret = 1;for(; e > 0; e >>= 1){if(e & 1) ret = (ret * p) % M;p = (p * p) % M;} return ret;}
Long gcd(Long a,Long b){if(b==0)return a;return gcd(b,a%b);}
Long modinverse(Long a,Long M){return bigmod(a,M-2,M);}
void io(){freopen("/Users/MyMac/Desktop/in.txt","r",stdin);}

/*************************** END OF TEMPLATE ****************************/

const int N = 1001;
Long xo(Long t)
{
      if(t%4==0) return t;
      if(t%4==1) return 1;
      if(t%4==2) return t+1;
      if(t%4==3) return 0;
      return 0;
}

Long xol(Long a)
{
      if(a%2 == 0) {
            auto k = a/2;
            k = xo(k);
            return k * 2;
      }else {
            auto k = a/2;
            k = xo(k);
            return k * 2 + (((a/2) %2) == 0);
      }
      return 0;
}
int main()
{
      Di(q);
      for(int i= 0;i < q; i ++) {
            Long l,r;
            cin >> l >> r;
            cout << (xol(r) ^ xol(l-1)) << endl;
      }
      return 0;

}