1. 程式人生 > >【洛谷P2899】[USACO08JAN]手機網絡Cell Phone Network

【洛谷P2899】[USACO08JAN]手機網絡Cell Phone Network

是否 pan action class bsp inline for c++ ==

題目描述

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.

John想讓他的所有牛用上手機以便相互交流(也是醉了。。。),他需要建立幾座信號塔在N塊草地中。已知與信號塔相鄰的草地能收到信號。給你N-1個草地(A,B)的相鄰關系,問:最少需要建多少個信號塔能實現所有草地都有信號。

輸入輸出格式

輸入格式:

  • 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
輸出樣例#1:
2

分析

代碼裏面有

代碼

來自Slager_Z大神的。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define man 10050
int n,f[man][4];
//這裏的安全表示以x為根的子樹全部都安全
//這裏的不安全表示以x為根的子樹除了x都安全 
//f[][0]不放塔但安全 //f[][1]不放塔並且不安全 //f[][2]放塔但安全 //f[][3]放塔還是不安全(肯定不存在,所以不用考慮) struct edge{int next,to;}e[man<<2]; int head[man<<2],num=0; inline void add(int from,int to) {e[++num].next=head[from];e[num].to=to;head[from]=num;} void treedp(int x,int fa) { f[x][0]=f[x][1]=0;f[x][2]=1;int minn=12456789;//當f[][2]時,初始值肯定有他自身的價值 bool changed=0;//記錄是否要更改f[x][0]的值 for(int i=head[x];i;i=e[i].next) { int to=e[i].to; if(to==fa)continue;//防止重新搜回去 treedp(to,x); minn=min(minn,f[to][2]-f[to][0]);//預處理如果將一個點從不放塔變為放塔,那麽他的最小代價是多少 f[x][0]+=min(f[to][0],f[to][2]);//先把最小的價值加上去,如果不行的話下面再改; if(f[to][2]<=f[to][0]) changed=1;//如果放了塔的價值比不放塔的價值還小,那麽肯定放塔咯,因為放塔了還可以多照看幾個地方(並且還可以把他的父親一起看了) f[x][1]+=f[to][0];//本身的f[][1]就是表示不放塔並不安全,那麽只能叫它這麽繼續錯下去,因為是當前這個點變得安全是f[][0]和f[][2]的責任,不需要f[][1]的幹涉 f[x][2]+=min(f[to][0],min(f[to][1],f[to][2]));//因為當前放了塔並且安全,那麽他的子樹放不放塔肯定都安全,所以子節點的任何狀態都可以成立 } if(changed==0) f[x][0]+=minn;//如果他的子樹都不放塔,那麽當前的節點就不安全了,所以必須把他的子節點中放塔的代價最小的點放塔,這樣才能保證他的安全 } int main() { scanf("%d",&n); for(int i=1;i<n;i++) { int u,v; scanf("%d%d",&u,&v); add(u,v);add(v,u); } treedp(1,-1); printf("%d\n",min(f[1][0],f[1][2])); return 0; }

【洛谷P2899】[USACO08JAN]手機網絡Cell Phone Network