牛客算法周周练2 - 完全平方数(打表、lower_bound、upper_bound)

牛客算法周周练2 - 完全平方数(打表、lower_bound、upper_bound)

链接:https://ac.nowcoder.com/acm/contest/5203/C
来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

多次查询 [l,r] 范围内的完全平方数个数

定义整数x为完全平方数当且仅当可以找到整数y使得y*y=x

输入描述:

第一行一个数n表示查询次数
之后n行每行两个数l,r

输出描述:

对于每个查询,输出一个数表示答案

示例1

输入

5
1 3
1 4
2 4
4 4
1 1000000000

输出

1
2
1
1
31622

备注:

n <= 100000
0<= l <= r <= 1000000000

 

先预处理出[0,1000000000]中的所有的完全平方数,共31623个(02~316222)。

二分查找出第一个大于等于 l 的完全平方数的位置下标,二分查找出第一个大于 r 的完全平方数的位置下标,将其相减即为答案。

可以分别用lower_bound()和upper_bound()

 

 1 #include <bits/stdc++.h>
 2 typedef long long LL;
 3 #define pb push_back
 4 const int INF = 0x3f3f3f3f;
 5 const double eps = 1e-8;
 6 const int mod = 1e9+7;
 7 const int maxn = 1e5+10;
 8 using namespace std;
 9 
10 vector<int> vt;
11 
12 int main()
13 {
14     #ifdef DEBUG
15     freopen("sample.txt","r",stdin); //freopen("data.out", "w", stdout);
16     #endif
17     
18     for(int i=0;i*i<=1000000000;i++)
19     vt.pb(i*i);
20 
21     int T;
22     scanf("%d",&T);
23     while(T--)
24     {
25         int l,r;
26         scanf("%d %d",&l,&r);
27         int pos1=lower_bound(vt.begin(),vt.end(),l)-vt.begin();
28         int pos2=upper_bound(vt.begin(),vt.end(),r)-vt.begin();
29         printf("%d\n",pos2-pos1);
30     }
31     
32     return 0;
33 }

 

 

-

posted @ 2020-04-23 02:12  jiamian22  阅读(278)  评论(0编辑  收藏  举报