At line 41 and 42, after you erase these two items, you don't want to increment j because the j'th item is now the new item. Also you want to break out of the k loop once you find a match.
I think you'll find that your code runs too slow when the input is very large. You've made a common mistake: representing the data as it is given to you, rather than in a way that is convenient for your algorithm. For example, consider creating an array of 5 integers. array[n] will be the number of groups with n members. Now with a little arithmetic you can match up groups and get your final answer.