Is it a tree?

Source: Internet
Author: User

Question: give you some directed edges (endpoint, with a length of 1) to determine whether the given graph is a tree.

Analysis: Graph Theory, and query sets. A tree is a directed acyclic graph (Forest is not connected) connected to all vertices ).

You can determine whether a ring exists according to the definition of the tree. There are two types of rings:

1. chain rings; 2. There are nodes with multiple Father's Day points;

In both cases, you only need to use and check the set to determine whether there is a number of sets before merging,

In a unified set, this edge must form a ring;

Note that the decision cannot be a forest.

Note: accuracy is a problem that has no data scope.

#include <iostream>#include <cstdlib> #include <cstdio>using namespace std;int used[100001];int sets[100001],rank[100001];int set_root(int a){if (a != sets[a])sets[a] = set_root(sets[a]);return sets[a];}int main(){int a,b,t = 1;while (~scanf("%d%d",&a,&b) && a >= 0 && b >= 0) {for (int i = 0 ; i < 100000 ; ++ i) {sets[i] = i;used[i] = rank[i] = 0;}int flag = 1;while (a||b) {if (set_root(a) == set_root(b))flag = 0;if (flag) {used[a] = used[b] = 1;sets[set_root(b)] = set_root(a);}scanf("%d%d",&a,&b);}if (flag == 1) {int count = 0;for (int i = 0 ; i < 100000 ; ++ i)if (used[i] && set_root(i) == i)if (count ++) {flag = 0;break;}}if (flag == 0)printf("Case %d is not a tree.\n",t ++);else printf("Case %d is a tree.\n",t ++);}return 0;}

Is it a tree?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.