CODEVS-1074-food chain-parallel query set, codevs-1074-food chain
Description
Three animals A eat B, B eat C, C eat.
1, a, B indicates a, B is similar
2, a, B indicates that a eats B
Determine the number of counterfeits
Analysis
- I have read NOIp before, but not at the time. Now I understand it a little abstract.
- Merge and query sets by weight
- X that can determine the relationship, and y's find has the same ancestor.
- Pa [x] is the ancestor of x, and r [x] is the distance from x to the ancestor. There are three types: 0, 1, 2. 0 indicates the same type as the ancestor; 1 indicates that the ancestor can be eaten; 2 indicates that the ancestor is eaten. r [find (x)] Must be 0. I used assert to verify it.
- When searching, the current ancestor px of x is recorded first. We can see that when the relationship between x and px is initially determined, r [px] Must be 0. after recursive find (px), the value of r [px] is the distance from px to its current ancestor. x and px are the same as their current ancestor, the distance from x to the current ancestor is the distance from x to the original px plus the distance from px to the current ancestor.
- When merging x and y, first px = find (x), py = find (y ). for example, if you want to set pa [px] To py, The py will not change. Consider how to change the rank of px. if the same type of x and y is required after merging, the distance from x to py should be equal to the r [y] at this time. so r [x] + r [px] = r [y], so r [px] = r [y]-r [x]. in this way, the new r [x] After path compression is equal to r [y.