A 数数
题意

思路
通过简单的数学变化:
第一个化成
(
1
+
2
+
.
.
.
n
)
2
(1+2+...n)^2
(1+2+...n)2。
第二个化成
n
!
2
n
n!^{2n}
n!2n
代码
过水已隐藏
B Galahad
题意
询问区间数的总和(重复出现的数只计算一次)。
思路
把询问按右端点排序,用树状数组维护当前区间的答案。
代码
#include <cstdio>
#include <algorithm>
struct node {
int l, r, id;
}q[500001];
int n, m;
int v[500001];
long long t[500001], a[500001], ans[500001];
bool operator <(const node &a, const node &b) {
return a.r < b.r;
}
void add(int pos, int val) {
for (; pos <= n; pos += pos & -pos)
t[pos] += val;
}
long long query(int pos) {
long long res = 0;
for (; pos; pos -= pos & -pos)
res += t[pos];
return res;
}
int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= m; i++)
scanf("%d %d", &q[i].l, &q[i].r), q[i].id = i;
std::sort(q + 1, q + m + 1);
int pos = 1;
for (int i = 1; i <= m; i++) {
for (; pos <= q[i].r; pos++) {
if (v[a[pos]]) add(v[a[pos]], -a[pos]);
v[a[pos]] = pos;
add(pos, a[pos]);
}
ans[q[i].id] = query(q[i].r) - query(q[i].l - 1);
}
for (int i = 1; i <= m; i++)
printf("%lld\n", ans[i]);
}
C 烹饪
题意
从 n n n个数中取出任意数,使得这些数相加或相减可以表示任意正整数,求取数的方案数。
思路
裴蜀定理:
关于不定方程
a
x
+
b
y
=
c
ax+by=c
ax+by=c有整数解的充要条件是
(
a
,
b
)
∣
c
(a,b)|c
(a,b)∣c。
可推广到多个数的情况上,故选出来的数互质即可成为一个合法方案。
设 f [ i ] f[i] f[i]为选数的最大公约数为 i i i的方案,转移显然。
代码
#include <cstdio>
#include <algorithm>
int n, a;
int f[2001];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a);
for (int j = 1; j <= 2000; j++)
if (f[j]) (f[std::__gcd(a, j)] += f[j]) %= 998244353;
f[a]++;
}
printf("%d", (long long)f[1] % 998244353);
}
D 粉丝群
题意
选任意 n n n个数 a ( a ≥ 1 ) a(a\geq 1) a(a≥1)使其和为 2 n 2n 2n且没有任意一个集合中数的和为 n n n,求方案数和字典序为 k k k的方案的异或和。
思路
打表猜结论可发现:
n=1
2
n=2
1 3
3 1
n=3
1 1 4
1 4 1
2 2 2
4 1 1
n=4
1 1 1 5
1 1 5 1
1 5 1 1
5 1 1 1
n=5
1 1 1 1 6
1 1 1 6 1
1 1 6 1 1
1 6 1 1 1
2 2 2 2 2
6 1 1 1 1
可以发现只有
n
+
1
n+1
n+1这个数一直在跳,然后
n
n
n为奇数时,有
n
+
1
n+1
n+1中方案,且第
n
n
n行全是
2
2
2,然后就瞎搞。
代码
#include <cstdio>
long long n, k;
int main() {
scanf("%lld %lld", &n, &k);
printf("%lld\n%lld", n + (n & 1) - (n == 1), k == n && n & 1 ? 2 : n & 1 ? n + 1 : n);
}
总结
日常变菜,要多做题。后面剩几题应该是改不出了。。。。。
本文精选了算法竞赛中的经典题目,包括数数、烹饪、粉丝群等,详细解析了每道题目的题意、解题思路及代码实现,涵盖了树状数组、裴蜀定理、打表猜结论等多种算法技巧。
1350





