音无结弦之时,天使跃动之心。立于浮华之世,奏响天籁之音。.|

次林梦叶

园龄:3年3个月粉丝:21关注:2

树的dfs遍历----但是输入很特殊,单单靠输入形成不了树

Cut 'em all!

描述:

You're given a tree with nn vertices.

Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.

输入:

The first line contains an integer nn (1n1051≤n≤105) denoting the size of the tree.

The next n1n−1 lines contain two integers uu, vv (1u,vn1≤u,v≤n) each, describing the vertices connected by the ii-th edge.

It's guaranteed that the given edges form a tree.

输出:

Output a single integer kk — the maximum number of edges that can be removed to leave all connected components with even size, or 1−1 if it is impossible to remove edges in order to satisfy this property.

样例输入:

4
2 4
4 1
3 1

样例输出:

1

样例输入:

3
1 2
1 3

样例输出:

-1

样例输入:

10
7 1
8 4
8 10
4 7
6 5
9 3
3 5
2 10
2 5

样例输出:

4

样例输入:

2
1 2

样例输出:

0

注释:

In the first example you can remove the edge between vertices 11 and 44. The graph after that will have two connected components with two vertices in each.

In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is 1−1.

 

 

就是这道题,后来看了大佬的博客才知道,树可以看做一个特殊的图来存,即是用链表存储的方式两边存,然后因为树是不可以从子节点往父节点走的,所以要一个vis[N]看一下节点x 是否走过:

复制代码
 1 #include <iostream>
 2 #include <cstring>
 3 using namespace std;
 4 const int N = 1e5 + 10;
 5 int e[2*N], ne[2*N], h[N], idx = 0;
 6 void add(int a, int b)
 7 {
 8     e[idx] = b, ne[idx] = h[a], h[a] = idx++;
 9     return;
10 }
11 int ans = 0, vis[N];
12 // dfs 的作用是返回在x为根下,节点的数目(不含已经减去的):
13 int dfs(int x)
14 {
15     vis[x] = 1;
16     int temp = 1; //算上自己:
17     for (int i = h[x]; i != -1; i = ne[i])
18     {
19         int j = e[i];
20         if (vis[j] == 0)
21         {
22             int num=dfs(j);
23             temp += num;
24            /*  printf ("%d %d %d\n",j,num,temp); */
25         }
26     }
27     if (temp % 2 == 0 && temp != 0 && x!=1)
28     {
29         ans++;
30         return 0;
31     }
32     else
33         return temp;
34 }
35 int main()
36 {
37     memset(h, -1, sizeof(h));
38     int n;
39     scanf("%d", &n);
40     for (int i = 0; i < n-1; i++)
41     {
42         int a, b;
43         scanf("%d%d", &a, &b);
44         add(a, b), add(b, a);
45     }
46     if (n % 2 != 0)
47         printf("-1");
48     else
49     {
50         dfs(1);
51         printf("%d", ans);
52     }
53     return 0;
54 }
复制代码

 

本文作者:次林梦叶

本文链接:https://www.cnblogs.com/cilinmengye/p/16171842.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   次林梦叶  阅读(23)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起