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 - 1 bidirectional 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
题目相当于要求我们给一棵树上的某些点染色,使得所有的点周围(包括它本身)至少有一个点被染色了。
本来想用树形DP做的,后来发现一个更容易写的办法,即减枝。
对这棵树所有度为一的点进行分析,如果该点没有被染色,也没有被覆盖(即周围没有点被染色),就把它的子节点染色。因为它和子节点至少要有一个被染色,子节点被染色明显优于它被染色,避免了重复。然后删去它及子节点度减一,删去连接这两者的路。
如此重复,直到所有节点都被发现过为止。对于最后一个节点特别分析,如果该节点及周围节点没有被染色,则对它进行染色。
该算法的时间复杂度为O(n)。
感谢MacroM提供的源码(有改动)。
#include<stdio.h>
#include<string.h>
int main()
{
int T, i, j, p, q, n, k, t;
int map[105][105], color[105], degree[105];
scanf("%d", &T);
while (T--)
{
scanf("%d", &n);
memset(map, 0, sizeof(map));
memset(color, 0, sizeof(color));
memset(degree, 0, sizeof(degree));
for (i = 0; i < n - 1; i++)
{
scanf("%d%d", &p, &q);
map[p][q] = 1;
map[q][p] = 1;
degree[p]++;
degree[q]++;
}
k = n - 1; t = 1;
while (k)
for (i = 1; i <= n; i++)
if (degree[i] == 1)
for (j = 1; j <= n; j++)
if (map[i][j])
{
if (color[i] == 0) color[j] = 1;//表示被选中
else if (color[i] == 1 && color[j] == 0)
color[j] = -1;//表示被覆盖
map[i][j] = 0;
map[j][i] = 0;
k--;
degree[i]--;
degree[j]--;
t = j;
break;
}
if (!color[t]) color[t] = 1;
for (i = 1; i < n; i++)
printf("%d ", color[i] == 1);
printf("%d\n", color[n] == 1);
}
}
这是我第一次写博客,难免有所疏漏,还请不吝赐教。欢迎大家留言。