Friday, 10 February 2012

Codechef -> Practice -> Easy -> TheWayToAFriendsHouseIsNeverTooLong


Solution :



import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;

/**
 *
 * @author XCoder
 */
class TheWayToAFriendsHouseIsNeverTooLong {

    public static int readIntLine() throws IOException {
        return Integer.parseInt(br.readLine());
    }

    public static long readLongLine() throws IOException {
        return Long.parseLong(br.readLine());
    }
    private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    private static PrintWriter pw = new PrintWriter(System.out);

    static class Bean implements Comparable<Bean> {

        Integer x;
        Integer y;

        public int compareTo(Bean o) {
            if (this.x.intValue() == o.x.intValue()) {
                return o.y.compareTo(this.y);
            } else {
                return this.x.compareTo(o.x);
            }
        }

        Bean(String s) {
            x = Integer.parseInt(s.split(" ")[0]);
            y = Integer.parseInt(s.split(" ")[1]);
        }
    }

    public static void main(String[] args) throws IOException {
        int test = readIntLine();
        while (test-- > 0) {
            br.readLine();
            int noofpoints = readIntLine();
            ArrayList<Bean> lst = new ArrayList<Bean>();
            while (noofpoints-- > 0) {
                Bean temp = new Bean(br.readLine());
                lst.add(temp);
            }
            Collections.sort(lst);
//            for (Bean bb : lst) {
//                System.out.println(bb.x + "   " + bb.y);
//            }
            double dist = 0.0;
            for (int i = 0; i < lst.size() - 1; i++) {
                dist += distance(lst.get(i).x, lst.get(i).y, lst.get(i + 1).x, lst.get(i + 1).y);
            }
            pw.printf("%.2f\n",dist);
        }
        pw.flush();
        pw.close();
    }

    public static double distance(int x1, int y1, int x2, int y2) {
        double d = 0.0;
        d = Math.sqrt(((x2 - x1) * (x2 - x1)) + ((y2 - y1) * (y2 - y1)));
        return d;
    }
}

No comments:

Post a Comment