B. 逻辑表达式 1ll * max(a, b) * c == max(1ll * a * c, 1ll * b * c) 的运算结果不一定为 true。
C. 执行代码 cout << sizeof(a); 后,输出的结果为 1。
D.a>b 时,for (unsigned i = a; i > b; i++) 一定是一个死循环。
【答案】B 【考点】 C++ 程序设计 【解析】A 中 d 还是 int,这也是为什么 int 乘 int 容易溢出;B 中 c 为负数时左边小于右边,表达式为假;C 中应该输出 4,sizeof 是占用字节数而不是变量个数;D 中 i 增到 unsigned 最大值后再自增会变成 0,不一定符合循环条件。
#include <bits/stdc++.h>using namespace std;
int n, d;
int Dfs(int x, int dep) {
int mid = x + (1 << d - dep);
if (n == x + 1 || n == mid) return x;
if (n < mid) return Dfs(x + 1, dep + 1);
else return Dfs(mid, dep + 1);
}
int main() {
cin >> n >> d;
cout << Dfs(1, 1) << endl;
return 0;
}
#include <bits/stdc++.h>using namespace std;
const int N = 20;
int n, m, x, y, son[N];
long long dp[1 << N];
int main() {
cin >> n >> m;
for (int i = 0; i < m; i++) {
cin >> x >> y;
son[y] |= (1 << x);
}
dp[0] = 1;
for (int s = 0; s < (1 << n); s++)
for (int x = 0; x < n; x++) {
if (s >> x & 1) continue;
if ((son[x] & s) != son[x]) continue;
dp[s | (1 << x)] += dp[s];
}
cout << dp[(1 << n) - 1] << endl;
return 0;
}
#include <bits/stdc++.h>using namespace std;
const int N = 1e6 + 5;
const int mod = 998244353;
int fac[N], invfac[N];
inline int qpow(int a, int n) {
int res = 1;
while (n != 0) {
res = 1ll * res * ((n % 2 == 1) ? a : 1) % mod;
a = 1ll * a * a % mod, n /= 2;
}
return res;
}
inline int calc(int x, int y) {
if (x < y) return 0;
return 1ll * fac[x] * invfac[y] % mod * invfac[x - y] % mod;
}
inline int init(const int N, const int mod) {
fac[0] = 1;
for (int i = 1; i <= N; i++)
fac[i] = 1ll * fac[i - 1] * i % mod;
invfac[N] = qpow(fac[N], mod - 2);
for (int i = N - 1; i >= 0; i--)
invfac[i] = 1ll * invfac[i + 1] * (i + 1) % mod;
}
int main() {
init(1000000, 998244353);
int t;
cin >> t;
while (t--) {
int n, m, k;
cin >> n >> m >> k;
int res = 0;
for (int i = 0; i <= k; i++)
(res += 1ll * calc(n, i) * calc(m, k - i) % mod) %= mod;
cout << res << endl;
}
return 0;
}
假设输入的 t,n,m,k 都是非负整数,满足 t,k≤1000,n,m≤106,k≤n,m。
【程序解释】 此程序使用逆元求组合数,并利用这点求解了 i=0∑kCni⋅Cmk−i。
27. 将第 9 行改为 if (n & 2) res = 1ll * res * a % mod; 后程序输出结果不会改变。
(链计数) 给定一个 n 个点 m 条边,编号为 0∼n−1 的有向无环图,求这个图中链的数目(链上至少有两个结点),对 109+7 取模。保证 n,m≤106。请补全程序。
C++
#include <bits/stdc++.h>using namespace std;
const int N = 1e6 + 5;
const int mod = 1e9 + 7;
int n, m, dp[N];
int tot, head[N], nxt[N], to[N];
inline void addedge(int x, int y) {
tot++, nxt[tot] = head[x];
head[x] = tot, to[tot] = y;
}
int Dfs(int x) {
if (~dp[x]) return dp[x];
if (①) return dp[x] = 1;
for (int i = head[x]; i != 0; i = nxt[i]) ②;
return dp[x];
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
③;
}
④;
int ans = 0;
for (int i = 1; i <= n; i++)
ans = (⑤) % mod;
cout << ans << endl;
return 0;
}
【解法提示】 用记忆化搜索求解链的数目:dp[x] 表示以 x 结尾的链数目,含一个点的链。答案是 ∑(dp[x]−1)。转移是 dp[x]=∑i→xdp[i]+1。