Bob enjoys playing computer games, especially strategic games, but sometimes he cannot find the solution fast enough and then he is very sad. Now he has the following problem. He must defend a medieval city, the roads of which form a tree. He has to put the minimum number of soldiers on the nodes so that they can observe all the edges. Can you help him?
Your program should find the minimum number of soldiers that Bob has to put for a given tree.
The input file contains several data sets in text format. Each data set represents a tree with the following description:
the number of nodes
the description of each node in the following format
node_identifier:(number_of_roads) node_identifier1 node_identifier2 ... node_identifier
or
node_identifier:(0)
The node identifiers are integer numbers between 0 and n-1, for n nodes (0 < n <= 1500). Every edge appears only once in the input data.
For example for the tree:
the solution is one soldier ( at the node 1).
The output should be printed on the standard output. For each given input data set, print one integer number in a single line that gives the result (the minimum number of soldiers). An example is given in the following table:
4 0:(1) 1 1:(2) 2 3 2:(0) 3:(0) 5 3:(3) 1 4 2 1:(1) 0 2:(0) 0:(0) 4:(0)
用的是贪心的写法,dfs o(n)效率 然后从叶子结点进行贪心,也是o(n)效率就是o(n),对于点覆盖问题,如果该节点和它父节点没有被访问过,则把父节点放入覆盖集合中,然后继续遍历。
#include
using namespace std;
const int maxn=3005;
int head[maxn],Set[maxn],visit[maxn],father[maxn],now,cnt,nowpos[maxn];
int n;
struct Node{
int to;
int next;
Node():to(0),next(0){
} ;
}node[maxn];
void init(){
memset(head,-1,sizeof(head));
memset(Set,0,sizeof(Set));
memset(visit,0,sizeof(visit));
memset(father,0,sizeof(father));
memset(nowpos,0,sizeof(nowpos));
now=0;
cnt=0;
}
int add_edge(int a,int b){
node[cnt].to=b;
node[cnt].next=head[a];
head[a]=cnt++;
node[cnt].to=a;
node[cnt].next=head[b];
head[b]=cnt++;
return 0;
}
int dfs(int x){
nowpos[now++]=x;
for(int k=head[x];k!=-1;k=node[k].next){
int b=node[k].to;
if(!visit[b]){
father[b]=x;//标记b的父节点
visit[b]=1;
dfs(b);
}
}
return 0;
}
int greedy(){
int res=0;
for(int i=n-1;i>=1;i--){//到1就可以了不需要最后一个点,因为是点覆盖呢
int b=nowpos[i];
if(!visit[b]&&!visit[father[b]]){
Set[father[b]]=1;
visit[father[b]]=1;
visit[b]=1;
res++;
//cout<<"res:"<