题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1054
题目:
Problem Description
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:
Sample Input
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)
Sample Output
1
2
题解:可以把题目转化成二分图求最小点覆盖。而最小点覆盖=最大边匹配。这题数据量有点大,所以用邻接矩阵会超时,Java里没有用Vector的,这里用链式前向星的方式建图。 其实这就是个匈牙利算法的模版题,建个无向图,结果除以2就是答案,我卡了好几个小时。。。差点以为数据出错了。因为wa的时间很短,也就是没过几组数据,可是写法应该是没问题的,又仔细看了看题,突然发现数据的输入有问题。。求括号里的值时,我没注意,想当然地只求了一位。。。改了之后就ac了。 这题还可以用树形dp做,不过这方面还不太熟,大家可以自行去学习学习。
代码:
import java.util.Arrays;
import java.util.Scanner;
//最小点覆盖或者树形dp都能做
//改了n遍代码一直过不去。。突然发现是读取数据时出问题了,我的num,也就是括号里的数只有一位。。
public class Main {
static class edge{
int v,next;
}
static int p[]=new int[2000];
static boolean vis[]=new boolean[2000];
static edge e[]=new edge[5000];
static int linked[]=new int[2000];
static int n,eid;
static void insert(int u,int v){
e[eid].v=v;
e[eid].next=p[u];
p[u]=eid++;
}
static boolean match(int u){
if(!vis[u]){
vis[u]=true;
for(int i=p[u];i!=-1;i=e[i].next){
int v=e[i].v;
if(!vis[v]){
vis[v]=true;
if(linked[v]==-1||match(linked[v])){
linked[v]=u;
//linked[u]=v;
return true;
}
}
}
}
return false;
}
static int hungry(){
int ans=0;
Arrays.fill(linked, -1);
for(int i=0;i<n;i++){
Arrays.fill(vis, false);
if(match(i)){
ans++;
}
}
return ans;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
n=sc.nextInt();
Arrays.fill(p, -1);
eid=0;
for(int i=0;i<e.length;i++){
e[i]=new edge();
}
for(int i=0;i<n;i++){
String s=sc.next();
String goal[]=s.split(":");
int u=Integer.valueOf(goal[0]);
//int num=goal[1].charAt(1)-'0';//!!!!!!!num不一定是个位数,不能这么求
//应该这么求num
int num=Integer.parseInt(goal[1].substring(1, goal[1].length()-1));
for(int j=0;j<num;j++){
int v=sc.nextInt();
insert(u,v);
insert(v,u);
}
}
System.out.println(hungry()/2);
}
sc.close();
}
}