A平方数

题目地址:

https://ac.nowcoder.com/acm/contest/6112/A

基本思路:

的范围是,所以我们枚举以内的数将它们的平方数打出来,然后对于每个我们二分查找,然后在找到的位置附近暴力找的最小值就是了。
写复杂了,由于并没有多次查询,所以不用二分直接找也可以。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF (int)1e18

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}

vector<int> vec;
int x;
signed main() {
  IO;
  for (int i = 0; i <= 1000001; i++) {
    vec.push_back(i * i);
  }
  sort(vec.begin(), vec.end());
  cin >> x;
  int sz = vec.size();
  int pos = lower_bound(vec.begin(), vec.end(), x) - vec.begin();
  int ans = 0, mn = INF;
  for (int i = max(0LL, pos - 1); i < min(sz, pos + 1); i++) {
    int dis = abs(vec[i] - x);
    if (dis < mn) {
      mn = dis;
      ans = vec[i];
    }
  }
  cout << ans << '\n';
  return 0;
}