Perfect Service
A network is composed of N computers connected by N − 1 communication links such that any two
computers can be communicated via a unique route. Two computers are said to be adjacent if there is
a communication link between them. The neighbors of a computer is the set of computers which are
adjacent to it. In order to quickly access and retrieve large amounts of information, we need to select
some computers acting as servers to provide resources to their neighbors. Note that a server can serve
all its neighbors. A set of servers in the network forms a perfect service if every client (non-server) is
served by exactly one server. The problem is to find a minimum number of servers which forms a
perfect service, and we call this number perfect service number.
We assume that N (≤ 10000) is a positive integer and these N computers are numbered from 1 to
N. For example, Figure 1 illustrates a network comprised of six computers, where black nodes represent
servers and white nodes represent clients. In Figure 1(a), servers 3 and 5 do not form a perfect service
because client 4 is adjacent to both servers 3 and 5 and thus it is served by two servers which contradicts
the assumption. Conversely, servers 3 and 4 form a perfect service as shown in Figure 1(b). This set
also has the minimum cardinality. Therefore, the perfect service number of this example equals two.
紫书上面的一道树型dp题目;
每个点有三种状态:
1、dp[i][0] 表示这个点是服务器;
它的儿子 j 结点可以是服务器,也可以不是;
2、dp[i][1] 表示这个点不是服务器,但是它的父亲是服务器;
它的儿子 j 结点必须不是服务器,并且儿子的父亲也不是服务器(就是结点 i );
3、dp[i][2] 表示这个点不是服务器,并且它的父亲也不是服务器;
它的儿子中必须要有个服务器,只能有一个;
知道了上述关系,那么式子就很容易推出来了;这道题比较坑的是dp[i][2]的计算,必须先初始化为一个超大数,还要防止它溢出;
代码:
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=10100;
const int M=4001000;
const LL mod=998244353;
struct Node{
int to,nex;
}edge[N<<1];
int head[N];
int cnt;
void add(int p,int q){
edge[cnt].to=q;
edge[cnt].nex=head[p];
head[p]=cnt++;
}
bool vis[N];
int dp[N][3];
void dfs(int p){
vis[p]=true;
dp[p][0]=1;
dp[p][1]=0;
dp[p][2]=M;
vector<int>ve;//装子节点
for(int i=head[p];~i;i=edge[i].nex){
int q=edge[i].to;
if(vis[q]) continue;
dfs(q);
ve.push_back(q);
dp[p][0]+=min(dp[q][0],dp[q][1]);
dp[p][1]+=dp[q][2];
}
for(int i=0;i<ve.size();i++) dp[p][2]=min(dp[p][2],dp[p][1]-dp[ve[i]][2]+dp[ve[i]][0]);
if(dp[p][0]>M) dp[p][0]=M;
if(dp[p][1]>M) dp[p][1]=M;
if(dp[p][2]>M) dp[p][2]=M;
return;
}
int main(){
ios::sync_with_stdio(false);
int n,t;
while(1){
cin>>n;
cnt=0;
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
int p,q;
for(int i=1;i<=n-1;i++){
cin>>p>>q;
add(p,q),add(q,p);
}
dfs(1);
cout<<min(dp[1][2],dp[1][0])<<endl;
cin>>t;
if(t==-1) break;
}
return 0;
}