NC24751. [USACO 2010 Nov G]Visiting Cows
描述
输入描述
* Line 1: A single integer: N
* Lines 2..N: Each line describes a single road with two space-separated integers: C1 and C2
输出描述
* Line 1: A single integer representing the maximum number of cows that Bessie can visit.
示例1
输入:
7 6 2 3 4 2 3 1 2 7 6 5 6
输出:
4
说明:
Bessie knows 7 cows. Cows 6 and 2 are directly connected by a road, as are cows 3 and 4, cows 2 and 3, etc.C++(g++ 7.5.0) 解法, 执行用时: 49ms, 内存消耗: 14812K, 提交时间: 2022-09-04 10:56:53
#include<bits/stdc++.h> using namespace std; #define int long long const int N=5e5+10; int n,dp[N][2]; vector<int> V[N]; void dfs(int u,int fa) { dp[u][1]=1; for(int i=0;i<V[u].size();i++) { int v=V[u][i]; if(v==fa) continue; dfs(v,u); dp[u][1]+=dp[v][0]; dp[u][0]+=max(dp[v][1],dp[v][0]); } } signed main() { cin>>n; for(int i=1,u,v;i<n;i++) { cin>>u>>v; V[u].push_back(v); V[v].push_back(u); } dfs(1,0); cout<<max(dp[1][0],dp[1][1]); return 0; }
C++14(g++5.4) 解法, 执行用时: 33ms, 内存消耗: 7256K, 提交时间: 2019-10-22 19:18:56
#include <bits/stdc++.h> #define ll long long using namespace std; const int N = 2e5+5; vector<int>a[N]; int dp[N][2]; void dfs(int x,int fa){ dp[x][1]=1; for(int i=0;i<a[x].size();i++){ int y=a[x][i]; if(y==fa)continue; dfs(y,x); dp[x][0]+=max(dp[y][1],dp[y][0]); dp[x][1]+=dp[y][0]; } } int main(){ int n;scanf("%d",&n); for(int i=1,x,y;i<n;i++){ scanf("%d%d",&x,&y); a[x].push_back(y);a[y].push_back(x); } dfs(1,0); printf("%d\n",max(dp[1][0],dp[1][1])); return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 55ms, 内存消耗: 4728K, 提交时间: 2020-02-26 20:58:56
#include<bits/stdc++.h> using namespace std; const int N=1e5+10; int dp[N][2]; vector<int>G[N]; int n; void dfs(int u,int fa) { dp[u][1]++; for(int v:G[u]) { if(v==fa) continue; dfs(v,u); dp[u][1]+=dp[v][0]; dp[u][0]+=max(dp[v][1],dp[v][0]); } } int main() { cin>>n; for(int i=1;i<n;++i) { int x,y; cin>>x>>y; G[x].push_back(y); G[y].push_back(x); } dfs(1,0); printf("%d\n",max(dp[1][0],dp[1][1])); }