21.P1164 小A点菜
使用一维数组优化, dp[j] = dp[j] + dp[j - a[i]];
可以选或者不选价格是a[i]的菜
#include<bits/stdc++.h>
using namespace std;
const int N = 1e4 + 10;
int n, m, a[N], dp[N];
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i ++)cin >> a[i];
for(int i = 1; i <= n; i ++)
{
dp[0] = 1;
for(int j = m; j >= a[i]; j --)
{
dp[j] = dp[j] + dp[j - a[i]];
}
}
cout << dp[m];
return 0;
22.P1192 台阶问题
每一层台阶i都可以从i - k到i之间的台阶到达
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, p = 100003;
int n, k, dp[N];
int main()
{
cin >> n >> k;
dp[0] = 1;
for(int i = 1; i <= n ; i ++)
{
for(int j = max(0, i - k); j < i; j ++)
{
dp[i] = (dp[i] + dp[j]) % p;
}
}
cout << dp[n];
return 0;
}
23.P1170 兔八哥与猎人
需要使两人构成的直角边互质,互质时两人之间就没有遮挡物,兔八哥就会死亡
#include<bits/stdc++.h>
using namespace std;
int n, xx1, xx2, yy1, yy2;
int abbs(int a)
{
return a > 0 ? a : -a;
}
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
int main()
{
cin >> n;
while(n --)
{
cin >> xx1 >> yy1 >> xx2 >> yy2;
if(gcd(abbs(xx1 - xx2), abbs(yy1 - yy2)) != 1)cout << "yes" << '\n';
else cout << "no" << '\n';
}
return 0;
}
24.P1181 数列分段 Section I
贪心,注意细节
#include<bits/stdc++.h>
using namespace std;
long long n, m, x, sum, ans;
int main()
{
cin >> n >> m;
for(int i = 1; i <= n; i ++)
{
cin >> x;
if(sum + x < m)
{
sum += x;
if(i == n)ans ++;
}
else if(sum + x == m)
{
ans ++;
sum = 0;
}
else if(sum + x > m)
{
ans ++;
sum = x;
}
}
cout << ans;
return 0;
}
25.P1364 医院设置
可以将每一层不断递归最后将递归点的答案全部相加即为在此点建立医院的全部贡献,循环每一个点,取分别在每一个点建立医院的最小值
注:一个点的权值 * 这个点的深度,为这个点在这一层的深度。
建立边时需要双向建立
#include<bits/stdc++.h> using namespace std; typedef long long LL; const int N = 2e5 + 10, inf = 2e5 + 10; bool vis[N]; vector<int> g[N]; LL n, u, v, a[N], dep[N]; LL dfs(int x) { LL res = a[x] * dep[x]; vis[x] = true; for(auto i : g[x]) { if(vis[i])continue; dep[i] = dep[x] + 1; res += dfs(i); } return res; } int main() { ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); cin >> n; for(int i = 1; i <= n; i ++) { cin >> a[i] >> u >> v; if(u)g[i].push_back(u), g[u].push_back(i); if(v)g[i].push_back(v), g[v].push_back(i); } LL ans = inf; for(int i = 1; i <= n; i ++) { dep[i] = 0; memset(vis, 0, sizeof vis); ans = min(ans, dfs(i)); } cout << ans; return 0; }