codeforces 979D Kuro and GCD and XOR and SUM

时间:2024-01-05 14:16:50

题意:

给出两种操作:

1.添加一个数字x到数组。

2.给出s,x,k,从数组中找出一个数v满足gcd(x,k) % v == 0 && x + v <= s && (x xor v 最大),如果没有,输出-1.

思路:

有两种做法。

第一种,首先用若干个set存因子中有k的数字。

然后每次在set[k]中二分找到大于s-x的第一个数,然后从大到小开始找,假设sum为当前x xor v的最大值,那么当当前的*it +x < sum,那么就直接break,原理是因为a ^ b <= a + b。

这个没有优化之前是会tle,但是加了优化之后比字典树跑得快了许多。。。

第二种,对于每一个数,都把它添加到它的因子的01字典树当中去,然后根据x xor v最大这个经典问题,找 xor 最大,字典树是个好东西。

代码1;

 #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <set>
#include <math.h>
using namespace std;
const int N = 1e5 + ;
set<int> mmp[N];
int main()
{
int n;
scanf("%d",&n);
while (n--)
{
int t;
scanf("%d",&t);
if (t == )
{
int u;
scanf("%d",&u);
int m = sqrt(1.0 * u);
for (int i = ;i <= m;i++)
{
if (u % i == )
{
mmp[i].insert(u);
mmp[u/i].insert(u);
}
}
}
else
{
int x,k,s;
scanf("%d%d%d",&x,&k,&s);
int sum = -;
int ans = -;
if (x % k)
{
printf("%d\n",ans);
continue;
}
auto it = mmp[k].upper_bound(s-x);
if (mmp[k].empty() || it == mmp[k].begin())
{
printf("%d\n",ans);
continue;
}
--it;
for (;it != mmp[k].begin();--it)
{
if (sum > x + *it) break;
if (sum < (x ^ *it))
{
ans = *it;
sum = x ^ *it;
}
}
if (sum < (x ^ *it))
{
ans = *it;
sum = x ^ *it;
}
printf("%d\n",ans);
}
}
return ;
}

代码2:

 #include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <set>
using namespace std;
const int N = 1e5 + ;
set<int> g[N];
struct node
{
int mi;
struct node* bit[];
node()
{
mi = N;
bit[] = bit[] = nullptr;
}
};
node *a[N];
void update(int x,int u)
{
node* cu = a[x];
cu -> mi = min(cu -> mi,u);
for (int i = ;i >= ;i--)
{
int b = u >> i & ;
if (cu -> bit[b] != nullptr)
{
cu = cu -> bit[b];
cu -> mi = min(cu -> mi,u);
}
else
{
cu -> bit[b] = new node();
cu = cu -> bit[b];
cu -> mi = min(cu -> mi,u);
}
}
}
int que(int x,int k,int s)
{
node *cu = a[k];
if (x % k || cu -> mi > s - x) return -;
int ret = cu -> mi;
for (int i = ;i >= ;i--)
{
int b = x >> i & ;
if (cu -> bit[b^] != nullptr && cu -> bit[b^] -> mi + x <= s)
{
cu = cu -> bit[b^];
ret = cu -> mi;
}
else
{
cu = cu -> bit[b];
ret = cu -> mi;
}
}
return ret;
}
int main()
{
int q;
for (int i = ;i < N;i++)
{
for (int j = i;j < N;j += i)
{
g[j].insert(i);
}
}
for (int i = ;i < N;i++) a[i] = new node();
scanf("%d",&q);
while (q--)
{
int t;
scanf("%d",&t);
if (t==)
{
int u;
scanf("%d",&u);
for (auto x : g[u])
{
update(x,u);
}
}
else
{
int x,s,k;
scanf("%d%d%d",&x,&k,&s);
int ans = que(x,k,s);
printf("%d\n",ans);
}
}
return ;
}