2026-01-16
CF
Problem - 566F - Codeforces(dp好题)
算因数,改求每个数字的倍数
调和级数时间复杂度:\(O(nlogn)\)
#include <bits/stdc++.h>
using namespace std;
#define LL long long
const LL mod = 998244353;
const int N=1e6+10;
int dp[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
int maxx = 0;
for (int i = 0, x; i < n;i++){
cin >> x;
dp[x]++;
maxx = max(dp[x], maxx);
for (int j = 2; j * x <= 1000000;j++){
dp[j * x] = max(dp[j * x], dp[x]);
}
}
cout << maxx << endl;
}
Problem - 1741E - Codeforces(dp好题)
一道很好想的dp题
注意多测清空啊!!!
#include <bits/stdc++.h>
using namespace std;
#define LL long long
const LL mod = 998244353;
const int N=2e5+10;
int dp[N],a[N];
void solve()
{
int n;
cin >> n;
memset(dp, 0, sizeof dp);
for (int i = 1; i <= n;i++){
cin >> a[i];
}
dp[0] = 1;
for (int i = 1; i <= n;i++){
if(i+a[i]<=n)
dp[i + a[i]] |= dp[i-1];
if (i - a[i] - 1>=0)
dp[i] |= dp[i - a[i]-1];
}
if(dp[n]==1){
cout << "YES\n";
}else{
cout << "NO\n";
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while (T--)
{
solve();
}
}
Problem - 1056D - Codeforces
输入要求: The second line contains \(n−1\) integers \(p_2, p_3, ..., p_n (1≤p_i<i)\), where \(pi\) means there is a branch between junctions \(i\) and \(p_i\). It is guaranteed that this set of branches forms a tree.
理解: 对于每个\(i\) ,其父结点是\(p_i\),因为要考虑到\(1\) 是根结点
这题卡在题目读不清楚啊啊啊啊
从下往上看,对于底下的结点,让它的每个子结点颜色都不同,就能使这个点快乐
所以只要统计每个点(包括本身的子节点数),然后排序即可
如果一个结点是快乐的,那么其子树中的所有结点也都是快乐的。
注意: He will put a light bulb of some color on each leaf junction and then count the number happy junctions. 这里涂色是只对叶子结点
所以在dfs中只对叶子结点数量置为1
#include <bits/stdc++.h>
using namespace std;
#define LL long long
const LL mod = 998244353;
const int N=1e5+10;
vector<int> e[N];
int sz[N];
void dfs(int now){
if(e[now].empty())
sz[now] = 1;
for (int i = 0; i < e[now].size();i++){
int son = e[now][i];
dfs(son);
sz[now] += sz[son];
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n;
cin >> n;
memset(sz, 0, sizeof sz);
for (int i = 2,x; i <= n;i++){
cin >> x;
e[x].push_back(i);
}
dfs(1);
sort(sz + 1, sz + 1 + n);
for (int i = 1; i <= n;i++){
cout << sz[i] << " ";
}
}

浙公网安备 33010602011771号