您的位置:首页 > 其它

zoj_最少点支配

2017-05-15 16:19 162 查看
Prohibition
Time Limit: 2 Seconds      Memory Limit: 65536 KB      Special Judge
Many people know Berland, the country that has been described at Saratov's contests for ten years. But this problem tells us about another country ― Beerland. Beerland has n cities
and n - 1bidirectional roads such that any city is reachable from the others, and the distance between two cities that are directly connected by a road can be passed in one day.
Despite the country's name, its new president introduced a prohibition. It is clear that atmosphere in the cities was heated up after that. To prevent the rebellion, the president decided
to place military squads at some cities in such a way that any city, if the rebellion fires up there, could be protected by some squad no later than in one day. Of course, the president cares about the budget of the country, so the number of military squads
should be minimal.

Input

There are multiple test cases. The first line of input is an integer T indicating the number of test cases. For each test case:
The first line of the input contains one integer n (1 <= n <= 100) - the number of cities in Beerland.
Each of next n - 1 lines contains two integers a and b (1 <= a, b <= n, a ≠ b) - the numbers of directly connected cities. Each
road is described exactly once.

Output

Output n numbers separated by space. The i-th number should be equal to 1 if the president should place a military squad in the i-th city, and 0 otherwise.
If there are many possible solutions, you can output any of them.

Sample Input

3
3
1 2
2 3
4
4 2
2 1
1 3
7
1 2
2 3
3 5
4 2
5 7
6 5

Sample Output

0 1 0
1 1 0 0
0 1 0 0 1 0 0

贪心思路+dfs从叶子结点开始

#include<bits/stdc++.h>
using namespace std;
#define maxn 205
struct Node{
int to;
int next;
Node():to(0),next(0){
}
}node[maxn];
int head[maxn],cnt=0,select[maxn],Set[maxn],p[maxn],now=0,newpos[maxn],n;
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;
}
void init(){
memset(node,0,sizeof(node));
memset(head,-1,sizeof(head));
cnt=0;
memset(select,0,sizeof(select));
memset(Set,0,sizeof(Set));
memset(newpos,0,sizeof(newpos));
memset(p,0,sizeof(p));
now=0;
}
int dfs(int x){
newpos[now++]=x;
for(int k=head[x];k!=-1;k=node[k].next){
int b=node[k].to;
if(!select[b]){
select[b]=1;
p[b]=x;//b is one of x's sons
dfs(b);
}
}
return 0;
}
int greedy(){
int s[maxn];
memset(s,0,sizeof(s));
int res=0;
for(int i=n-1;i>=0;i--){
int t=newpos[i];
if(!s[t]){
if(!Set[p[t]]){
Set[p[t]]=1;//set i-th as one of V's vertex
res++;
}
s[t]=1;
s[p[t]]=1;
s[p[p[t]]]=1;
}
}
return res;
}
int main(){
int t;
cin>>t;
while(t--){

cin>>n;
init();
for(int i=1;i<n;i++){
int a,b;
cin>>a>>b;
add_edge(a,b);
}
select[1]=1;
p[1]=1;
dfs(1);
greedy();
for(int i=1;i<=n;i++){
cout<<Set[i];
if(i!=n)cout<<" ";
}
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: