Code for checking the food chain (c)
Address: http://blog.csdn.net/caroline_wendy
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 <stdio.h>/* * main.cpp * * Created on: 2014.7.20 * Author: spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <memory.h>#include <limits.h>#include <algorithm>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<n; i++) {par[i] = i;rank[i] = 0;}}int find (int x) {if(par[x] == x) {return x;} else {return par[x] = find(par[x]);}}void unite(int x, int y) {x = find(x);y = find(y);if (x == y) return;if (rank[x] < rank[y]) {par[x] = y;} else {par[y] = x;if (rank[x] == rank[y]) rank[x]++;}}bool same(int x, int y) {return find(x) == find(y);}};class Program {static const int MAX_N = 100;int N = 100, K = 7;int T[MAX_N] = {1, 2, 2, 2, 1, 2, 1},X[MAX_N] = {101, 1, 2, 3, 1, 3, 4},Y[MAX_N] = {1, 2, 3, 3, 3, 1, 4};DisjoinSet DS;public:void solve() {DS.init(N*3);int ans = 0;for (int i=0; i<K; i++) {int t = T[i];int x = X[i]-1, y = Y[i]-1;if (x<0 || N<=x || y<0 || N<=y) {ans ++;continue;}if (t==1) {if (DS.same(x, y+N) || DS.same(x, y+2*N)) {ans++;} else {DS.unite(x, y);DS.unite(x+N, y+N);DS.unite(x+N*2, y+N*2);}} else { if (DS.same(x,y) || DS.same(x, y+2*N)) { ans++; } else { DS.unite(x, y+N); DS.unite(x+N, y+2*N); DS.unite(x+2*N, y); }}}printf("ans = %d\n", ans);}};int main(void){Program iP;iP.solve();return 0;}
Output:
ans = 3
Programming algorithms-food chain and code query (c)