Problem 1 based on graph. Needs optimization