Programming algorithms-food chain and code query (C)

Source: Internet
Author: User

Programming algorithms-food chain and code query (C)
Code for checking the food chain (C)

 

 

Question: There are N animals numbered 1, 2 ,..., n. all animals belong to one of A, B, and C. it is known that A eats B, B eats C, and C eats.

Two types of information are provided in order.

First, x and y belong to the same class.

Type 2: x eat y.

There may be errors and contradictions between the information, and the number of incorrect information is obtained.

 

For example:

N = 10 animals, given K = 7 messages.

(1) 1: x = 101, y = 1; error: No 101 animals.

(2) 2: x = 1, y = 2; animal 1 eats animal 2.

(3) 2: x = 2, y = 3; animal 2 eats animals 3.

(4) 2: x = 3, y = 3; error. Animal 3 cannot eat animal 3.

(5) 1: x = 1, y = 3; error: Animal 1 and animal 3 belong to the same type, and conflict with (2) (3.

(6) 2: x = 3, y = 1; animal 3 eats animal 1.

(7) 1: x = 5, y = 5; animal 5 and animal 5 belong to the same type.

Result = 3, that is, (1) (4) (5) error.

 

UseAnd query set (disjoint set)Solution.

Create 3 * N elements and check the set. Each group indicates the possible types of element I, x, 3 in total.

Merge and query the set. Find the conflict information.

 

Code:

 

/** Main. cpp ** Created on: 2014.7.20 * Author: Spike * // * eclipse cdt, gcc 4.8.1 */# include
 
  
/** Main. cpp ** Created on: 2014.7.20 * Author: spike * // * eclipse cdt, gcc 4.8.1 */# include
  
   
# Include
   
    
# Include
    
     
# Include using namespace std; class DisjoinSet {static const int MAX_N = 10000; int par [MAX_N]; int rank [MAX_N]; public: void init (int n) {for (int I = 0; I
     
      Output:
      

 

 

ans = 3


 

 

 

 

 

Related Article

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.