NC24953. [USACO 2008 Jan G]Cell Phone Network
描述
输入描述
* Line 1: A single integer: N
* Lines 2..N: Each line specifies a pair of adjacent pastures with two space-separated integers: A and B
输出描述
* Line 1: A single integer indicating the minimum number of towers to install
示例1
输入:
5 1 3 5 2 4 3 3 5
输出:
2
说明:
The towers can be placed at pastures 2 and 3 or pastures 3 and 5.C++(g++ 7.5.0) 解法, 执行用时: 6ms, 内存消耗: 960K, 提交时间: 2023-02-18 22:27:15
#pragma GCC optimize(2) #include <bits/stdc++.h> using namespace std; typedef long long ll; constexpr int inf=0x3f; int ans; int vis[10005]; vector<int> e[10005]; void dfs(int u,int fa) { int flag=0; for(auto v:e[u]) { if(v==fa) continue; dfs(v,u); flag|=vis[v]; } if(!flag&&!vis[u]&&!vis[fa]) { vis[fa]=1,ans++; } } int main() { ios::sync_with_stdio(0); int n; cin>>n; for(int i=1;i<=n;++i) { int x,y; cin>>x>>y; e[x].push_back(y); e[y].push_back(x); } dfs(1,0); cout<<ans; return 0; }
C++11(clang++ 3.9) 解法, 执行用时: 12ms, 内存消耗: 1096K, 提交时间: 2020-03-29 13:22:23
#include<bits/stdc++.h> using namespace std; int n,ans=0; vector<int>f[20010]; int dfs(int u,int p) { int ch=-1; for(int i=0;i<f[u].size();i++) { int val=f[u][i]; if(val!=p) { int ret=dfs(val,u); if(ret==-1) ch=1; else if(ret==1&&ch!=1) ch=0; } } if(ch==1) ans++; return ch; } int main() { cin>>n; for(int i=1;i<n;i++) { int a,b; cin>>a>>b; f[a].push_back(b); f[b].push_back(a); } if(dfs(1,0)==-1) ans++; cout<<ans<<"\n"; return 0; }