kanm7 @ 2022-06-02 23:21:26
求解,这样做思路哪里不对
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1510;
int h[N * 2], e[N * 2], ne[N * 2], idx;
int n;
bool vis[N];
int f[N][2];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u) // 计算出 f[u][0] 和 f[u][1]
{
f[u][1] = 1;
vis[u] = true;
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (!vis[j])
{
cout << u << ' ' << j << endl;
dfs(j);
}
else
continue;
f[u][0] += f[j][1];
f[u][1] += min(f[j][1], f[j][0]);
}
return;
}
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
while (cin >> n)
{
memset(h, -1, sizeof h);
memset(vis, 0, sizeof vis);
idx = 0;
for (int i = 0; i < n; i++)
{
int id, k, x;
cin >> id >> k;
while (k--)
{
cin >> x;
add(id, x);
add(x, id);
}
}
dfs(0);
int t = min(f[0][0], f[0][1]);
cout << t << endl;
}
return 0;
}
by 035966_L3 @ 2022-06-02 23:34:16
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1510;
int h[N * 2], e[N * 2], ne[N * 2], idx;
int n;
bool vis[N];
int f[N][2];
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void dfs(int u, int fa) // 计算出 f[u][0] 和 f[u][1]
{
f[u][1] = 1;
vis[u] = true;
for (int i = h[u]; i != -1; i = ne[i])
{
int j = e[i];
if (j == fa) continue;
if (!vis[j])
{
//cout << u << ' ' << j << endl;
dfs(j, u);
}
else
continue;
f[u][0] += f[j][1];
f[u][1] += min(f[j][1], f[j][0]);
}
return;
}
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
while (cin >> n)
{
memset(h, -1, sizeof h);
memset(vis, 0, sizeof vis);
idx = 0;
for (int i = 0; i < n; i++)
{
int id, k, x;
cin >> id >> k;
while (k--)
{
cin >> x;
add(id, x);
add(x, id);
}
}
dfs(0, -1);
int t = min(f[0][0], f[0][1]);
cout << t << endl;
}
return 0;
}
dfs 处理子树时不能让它往上找父亲,否则死递归 TLE+MLE。
(我一个不会树形 dp 的竟然调出来了……)
by 035966_L3 @ 2022-06-02 23:34:47
@kanm7
by 035966_L3 @ 2022-06-02 23:36:01
@kanm7 实际上,是您的 vis 数组忘记在 dfs 前更新了……
by kanm7 @ 2022-06-13 18:51:59
@035966_L3 谢谢大哥lll