D1. All are Same
题意:
给一个数组,选择一个数
k
k
k,每次选一个数减
k
k
k,操作次数任意,要求最后减完,所有的数都相等,求最大的
k
k
k。
如果
k
k
k 可以任意选择,则输出
−
1
-1
−1。
思路:
首先特判掉所有数都相等的情况,输出
−
1
-1
−1
然后他要求最后所有的数都相等,那么就相当于每个数都减了
p
i
p_i
pi 个
k
k
k,最后剩下
w
w
w
即
a
i
=
k
∗
p
i
+
w
a_i=k * p_i + w
ai=k∗pi+w,转化一下意思就是求所有数同余,最大的模数是多少
求一下差分,扫一遍求
g
c
d
gcd
gcd 即可
其实不求差分也一样,只需要选定区间内的一个数(任意选择,然后让其他数都减去它,扫一遍求 gcd 也可以,这也是 D2
c
h
e
c
k
check
check 函数的由来。(至于正确性的证明,我也不清楚~~~
这个题的简单版(D
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
using namespace std;
const int maxn = 1e5 + 9;
const int mod = 1e9 + 7;
ll n, m;
int a[maxn], b[maxn];
void work()
{
cin >> n;
set<int> se;
for(int i = 1; i <= n; ++i) cin >> a[i], se.insert(a[i]);
int d = 0;
for(int i = 2; i <= n; ++i)
b[i-1] = a[i] - a[i-1], d = __gcd(d, b[i-1]);
if(se.size() != 1)cout << abs(d) << endl;
else cout << -1 << endl;
}
int main()
{
ios::sync_with_stdio(0);
int TT;cin>>TT;while(TT--)
work();
return 0;
}
D2. Half of Same
题意:
在D1的基础上,要求最后剩余的数,至少一半相等即可
思路:
预处理一下所有两个数的差值
d
i
f
dif
dif(然鹅我并没有预处理,然后对于每一个
d
i
f
dif
dif 枚举因子,然后
c
h
e
c
k
check
check 一下,判断是否存在至少一半的
d
i
f
dif
dif 都含有这个因子,如果有,那么这个因子可以为答案。维护一下最大的因子即可
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
using namespace std;
const int maxn = 2e6 + 9;
const int mod = 1e9 + 7;
ll n, m;
bitset <maxn> vis;
int a[50];
int check(int x)
{
if(vis[x]) return 0;
vis[x] = 1;
for(int i = 1; i <= n; ++i)// 枚举 i 是选择的那至少一半数的其中一个
{
int cnt = 0;
for(int j = 1; j <= n; ++j)
if(abs(a[i] - a[j]) % x == 0)
++cnt;
if(cnt * 2 >= n) return x;
}
return 0;
}
void work()
{
cin >> n;
vis.reset();
int ans = 0;
for(int i = 1; i <= n; ++i) cin >> a[i];
for(int i = 1; i <= n; ++i)
if(count(a + 1, a + 1 + n, a[i]) * 2 >= n)
{
cout << -1 << endl;return;
}
for(int i = 1; i <= n; ++i)
for(int j = i + 1; j <= n; ++j)
{
int dif = abs(a[i] - a[j]);
for(int k = 1; k * k <= dif; ++k)
{
ans = max(ans, check(k));
ans = max(ans, check(dif / k));
}
}
cout << ans << endl;
}
int main()
{
ios::sync_with_stdio(0);
int TT;cin>>TT;while(TT--)
work();
return 0;
}
378

被折叠的 条评论
为什么被折叠?



