目录
C. Make it Simple
D. Swap to Gather
E. GCD of Subset
C. Make it Simple
看当前输入的两个点作为一对是否被标记过,用 set 判重就可以了
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5 + 5, INF = 1e18;
int T, n, m, cnt, ans;
string s;
set<pair<int, int> > se;
signed main()
{
cin >> n >> m;
for (int i = 1; i <= m; i ++)
{
int u, v;
cin >> u >> v;
if (u == v || se.find({u, v}) != se.end() || se.find({v, u}) != se.end())
{
ans ++;
continue;
}
se.insert({u, v});
se.insert({v, u}); // 两个都要加
}
cout << ans;
return 0;
}
D. Swap to Gather
移动 0。对于每一个 0,要么移到其左侧所有 1 的左边,要么移到其右侧所有 1 的右边,选哪种看哪边 1 的个数少。正反两次前缀和。
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 5e5 + 5, INF = 1e18;
int T, n, cnt, ans, a[N], b[N];
string s;
signed main()
{
cin >> n >> s;
for (int i = 0; i < n; i ++)
if (s[i] == '1')
a[i] = a[i - 1] + 1;
else
a[i] = a[i - 1];
for (int i = n - 1; i >= 0; i --)
if (s[i] == '1')
b[i] = b[i + 1] + 1;
else
b[i] = b[i + 1];
for (int i = 0; i < n; i ++)
if (s[i] == '0')
ans += min(a[i], b[i]);
cout << ans;
return 0;
}
E. GCD of Subset
把找最大公因数的问题转化成从 1 开始枚举所有公因数看是否合法。
对于一个公因数 x,若序列 A 中至少有 k 个数是 x 的倍数时,x 合法。
目标:统计公因数 x,序列 A 中有多少个数是 x 的倍数
步骤:(1)统计序列 A 中每个数出现的个数
(2)枚举 x,mult [ x ] = cnt [ x ] + cnt [ 2x ] + cnt [ 3x ] + ...
(3)再次枚举 x,只要 mult [ x ] 大于题中给定的 k,x 就可以成为序列 A 中是 x 的整数倍的数的答案
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1200005, maxa = 1e6 + 5, INF = 1e18;
int T, n, k, a[N], ans[maxa], cnt[maxa], mult[maxa];
string s;
signed main()
{
cin >> n >> k;
for (int i = 1; i <= n; i ++)
{
cin >> a[i];
cnt[a[i]] ++;
}
for (int i = 1; i <= maxa; i ++)
for (int j = i; j <= maxa; j += i)
mult[i] += cnt[j];
for (int i = 1; i <= maxa; i ++)
if (mult[i] >= k)
for (int j = i; j <= maxa; j += i)
ans[j] = max(ans[j], i);
for (int i = 1; i <= n; i ++)
cout << ans[a[i]] << '\n';
return 0;
}