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