infinite sequence

1129 -- [Mock test questions] Infinite sequence

Description

  We generate the sequence in the following way:
  1. The sequence at the beginning is: "1";
  2. Each change turns "1" in the sequence into "10" and "0" into "1". 
  After infinite changes, we get the sequence "1011010110110101101...".
  There are Q queries in total, and each query is: how many 1s are there between the interval A and B.
  Task: Write a program to answer Q queries

Input

  The first line is an integer Q,
  followed by Q lines, each line contains two integers a and b separated by spaces.

Output

  There are Q lines of output, one answer per line.

Sample Input

1

2 8

Sample Output

4

Hint

  1 <= Q <= 5000 ,1 <= a <= b < 2^63

 

#include<iostream>
#include<iomanip>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
long long i,j,a,b,f[100];
long long w(long long m) {
	int n;
	if(m==0) return 0;
	if(m==1) return 1;
	if(m==2) return 1;
	for(j=1; j<=100; j++) {
		if(f[j]<=m&&f[j+1]>=m) {
			n=j;
			break;
		}
	}
	return w(m-f[n])+f[n-1];
}
int main() {
	int q;
	cin>>q;
	f[0]=0;
	f[1]=1;
	for(i=2; i<=100; i++) {
		f[i]=f[i-1]+f[i-2];
	}
	for(i=1; i<=q; i++) {
		cin>>a>>b;
		cout<<w(b)-w(a-1)<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_39440588/article/details/81151678