Please checkout this question and explain me how to approach it
http://codeforces.com/contest/76/problem/F