Friend Numbers ACM ICPC

Hi All,
I am trying to solve this problem https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2013.

The approcah I am thinking is that after extracting distinct elements , we can do Cartesian Product
like A * A * A…A in ordered way. This will give us numbers in increasing order. Also we need to eliminate first and last number for every cartesian product. Because that will give elements containing same elements. eg {1,2} * {1,2) = {11,12,21,22}…Here we need to eliminate 11 and 22 for counting only.

Any other suggestion on this. Or Any other approach.

//