working and passing spoj 051

working and passing spoj 051
NEEDS cleaning and simplifing