标签:scanf pac dfs mes 自己 fabs fstream lib namespace
题目链接:https://www.nowcoder.com/acm/contest/87/G
分析:
1、对于点cur,dp[cur][0]表示在该点住宿;dp[cur][1]表示其某个子结点住宿,自己被访问到;dp[cur][2]表示其父结点住宿,自己被访问到;
2、如果dp[cur][0],则cur的子结点全是2状态
3、如果dp[cur][2],则cur的子结点要么为0状态,要么为1状态,取这两个状态的最大值累加。
4、如果dp[cur][1],则cur的子结点至少有一个为0状态,其余的为1状态,同样是取两个状态的最大值累加;
不过,若每个子结点都是取1状态时为最优,则必须在他们当中找出一个损失最小的0状态,所以记录每个结点1状态与0状态差值的最小值,然后将变为0状态后损失最小的结点变为0状态即可。
#include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<fstream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define lowbit(x) (x & (-x)) const double eps = 1e-8; inline int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a > b ? 1 : -1; } typedef long long LL; typedef unsigned long long ULL; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const LL LL_INF = 0x3f3f3f3f3f3f3f3f; const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const double pi = acos(-1.0); const int MAXN = 500000 + 10; const int MAXT = 10000 + 10; using namespace std; int dp[MAXN][3]; vector<int> v[MAXN]; int dfs(int cur, int id, int fa){ if(dp[cur][id] != -INT_INF) return dp[cur][id]; int len = v[cur].size(); if(id == 0){ dp[cur][id] = 1; for(int i = 0; i < len; ++i){ if(v[cur][i] == fa) continue; dp[cur][id] += dfs(v[cur][i], 2, cur); } } else if(id == 1 && v[cur].size() > 0){ dp[cur][id] = 0; int dif = INT_INF; bool ok = false; for(int i = 0; i < len; ++i){ if(v[cur][i] == fa) continue; if(dfs(v[cur][i], 0, cur) >= dfs(v[cur][i], 1, cur)){ ok = true; dp[cur][id] += dfs(v[cur][i], 0, cur); } else{ dp[cur][id] += dfs(v[cur][i], 1, cur); dif = min(dif, dfs(v[cur][i], 1, cur) - dfs(v[cur][i], 0, cur)); } } if(!ok){ dp[cur][id] -= dif; } } else if(id == 2){ dp[cur][id] = 0; for(int i = 0; i < len; ++i){ if(v[cur][i] == fa) continue; dp[cur][id] += max(dfs(v[cur][i], 0, cur), dfs(v[cur][i], 1, cur)); } } return dp[cur][id]; } int main(){ int n, s; scanf("%d%d", &n, &s); for(int i = 1; i <= n; ++i){ dp[i][0] = dp[i][1] = dp[i][2] = -INT_INF; } int x, y; for(int i = 0; i < n - 1; ++i){ scanf("%d%d", &x, &y); v[x].push_back(y); v[y].push_back(x); } printf("%d\n", dfs(s, 0, -1)); return 0; }
标签:scanf pac dfs mes 自己 fabs fstream lib namespace
原文地址:https://www.cnblogs.com/tyty-Somnuspoppy/p/9032190.html