AcWing 第59场周赛
AcWing 第59场周赛
https://www.acwing.com/activity/content/competition/problem_list/2015/
AcWing 4491. 数组操作
按题意模拟即可
注意小坑:前缀和包括第0项,多一个答案0
#include <bits/stdc++.h>
using namespace std;
int main () {
int minn = 0, ans = 0, sum = 0;
int n; cin >> n;
while (n --) {
int x;
cin >> x;
ans += x, sum += x;
minn = min (minn, sum);
}
cout << ans - minn;
}
AcWing 4492. 减法操作
对于给定的数n,有三种可能:
- n为质数,那么最小质因子就是本身,所以答案为1;
- n为偶数,最小质因子为2,减到0需要n/2次,答案为n/2
- n为奇数,暴力枚举找到最小质因子p(必为奇数),此时数字变为\(n-p\)(奇数相加减得偶数),转化为情况2,所以答案为\(1+(n-p)/2\)
#include <bits/stdc++.h>
#define int long long
using namespace std;
bool is_prime (int x) {
if (x == 2) return true;
for (int i = 2; i*i <= x; i ++)
if (x % i == 0) return false;
return true;
}
signed main () {
int n;
cin >> n;
//pre();
if (is_prime (n)) cout << 1;
else if (n % 2 == 0) cout << n/2;
else {
for (int i = 2; i <= n; i ++) {
if (is_prime (i) && n % i == 0) {
cout << (n-i) / 2 + 1;
break;
}
}
}
}
4493. 环形连通分量
找连通块,判环
由无向图 + 环 得性质:所有点的度数都是2
所以只需枚举每个集合,判断该集合中是否所有点的度数都是2
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int fa[N], d[N];
int n, m;
bool st[N]; //是否为环
int find (int x) {
if (x != fa[x])
fa[x] = find (fa[x]);
return fa[x];
}
int main () {
memset (st, true, sizeof st);
cin >> n >> m;
for (int i = 1; i <= n; i ++) fa[i] = i;
while (m --) {
int a, b;
cin >> a >> b;
fa[find (a)] = find (b);
d[a] ++, d[b] ++;
}
int cnt = 0;
for (int i = 1; i <= n; i ++)
if (d[i] != 2) st[find(i)] = false;
for (int i = 1; i <= n; i ++)
if (fa[i] == i && st[i]) cnt ++;
cout << cnt << endl;
}