POJ3659 Cell Phone Network
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 3782 | Accepted: 1305 |
Description
Farmer John has decided to give each of his cows a cell phone in hopes to encourage their social interaction. This, however, requires him to set up cell phone towers on his N (1 ≤N ≤ 10,000) pastures (conveniently numbered 1..N) so they can all communicate.
Exactly N-1 pairs of pastures are adjacent, and for any two pastures A and B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B) there is a sequence of adjacent pastures such that A is the first pasture in the sequence and B is the last. Farmer John can only place cell phone towers in the pastures, and each tower has enough range to provide service to the pasture it is on and all pastures adjacent to the pasture with the cell tower.
Help him determine the minimum number of towers he must install to provide cell phone service to each pasture.
Input
* 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
Output
* Line 1: A single integer indicating the minimum number of towers to install
Sample Input
5 1 3 5 2 4 3 3 5
Sample Output
2
Source
#include <stdio.h> #include <vector> #include <string.h> #define N 10005 #define INF 2000000 #define MIN(a,b) ((a)<(b)?(a):(b)) using namespace std; vector< int >gra[N]; int fa[N],dp[N][3],n; void dfs( int s, int f) { fa[s]=f; dp[s][0]=0; dp[s][1]=1; dp[s][2]=0; if (gra[s].size()==1&&gra[s][0]==f) { dp[s][2]=INF; return ; } int mark=0; for ( int i=0;i<gra[s].size();i++) { int t=gra[s][i]; if (t==f) continue ; dfs(t,s); dp[s][1]+=MIN(MIN(dp[t][0],dp[t][1]),dp[t][2]); dp[s][0]+=dp[t][2]; if (dp[t][1]<=dp[t][2]) { mark=1; dp[s][2]+=dp[t][1]; } else dp[s][2]+=dp[t][2]; } if (mark) return ; int temp=INF; for ( int i=0;i<gra[s].size();i++) { int t=gra[s][i]; if (t==f) continue ; temp=MIN(temp,dp[s][2]+dp[t][1]-dp[t][2]); } if (temp!=INF) dp[s][2]=temp; } void re( void ) { scanf ( "%d" ,&n); memset (fa,0, sizeof (fa)); memset (dp,0, sizeof (dp)); for ( int i=1;i<=n;i++) gra[i].clear(); for ( int i=1;i<n;i++) { int a,b; scanf ( "%d%d" ,&a,&b); gra[a].push_back(b); gra[b].push_back(a); } } void run( void ) { dfs(1,-1); printf ( "%d\n" ,MIN(dp[1][1],dp[1][2])); } int main() { re(); run(); } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 从零开始开发一个 MCP Server!
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Ai满嘴顺口溜,想考研?浪费我几个小时
· Browser-use 详细介绍&使用文档