http://codeforces.com/blog/entry/63046
Big spoilers ahead:
Dogs with the same tag are equivalent. Same for cats with the same tag. So, imagine a flow network where we "merge" all those into a single node. From s to each "cat-set", put an edge with capacity equal to the set's size. From each "dog-set" to t, put an edge with capacity equal to the set size. Put an edge from each "cat-set" to each "dog-set" having a different tag, with infinite capacity [this is important for the problem's model].
If you add the "sets of size 0" so that every set has a matching oposite set, the graph structure (except for the capacities) is completely fixed: it is almost a "complete bipartite", except for the edges going from vertex i on one side to vertex i on the other side.
Now, max-flow on that network would solve the problem. But let's compute min-cut instead: the network has so many edges that there are very few cuts to consider, and by max-flow = min-cut, that will be the solution.
Since the edges in the middle have infinite capacity, the min cut will never cut them, so we only need to consider cutting the other edges. The simplest possibility is cutting a whole side, which gives M or N as answers. If we leave the edge associated to vertex i on one side, without cutting it, then we are forced to cut the edges of every vertex on the other side, except for the corresponding vertex i. Applying the same reasoning to that other vertex, we must cut every single "outer" edge, except for the ones corresponding to both vertices "i". So, that gives only max(N, M)additional cuts to consider, apart from the previous two. The capacity of each one is M + N - ai - bi , where ai and biare the amount of cats and dogs with tag i.
So the final answer is min(M,N, min(over all i, M + N - ai - bi))