Having trouble Implementing a Custom Comparator for a TreeSet (Dijkstra's)

柔情痞子 提交于 2019-12-08 03:04:01

问题


I'm currently trying and implementing my own custom O(N.lgN) solution of Dijkstra's using Adjacency Lists. Now if you are familiar with this algorithm (most likely you are), I was having trouble storing the tuple for each Vertex. If you have no clue what i'm talking about, have alook at: http://qr.ae/LoESY

Tuples can easily be stored in C++ using

pair <int,int>.

Anyways, i found a solution to that and came to know, against all odds, that a similar class DOES exist its called the 'AbstractMap.SimpleEntry' Class. Details are given here:

https://stackoverflow.com/a/11253710/4258892

Now that you've read it, this works almost the same as pair<> and suffices to store the Adjacent Edge as the key and Weight as the Value in the tuple.

Declaration: Map.Entry pair= new AbstractMap.SimpleEntry(1,2);

Now i have all the inputs in the form of tuples stored in an ArrayList for each vector. I planned on adding the tuples of the source entered to the TreeSet and sort them in ascending order wrt the weights (right?). However, if i just add these tuples to the TreeSet, I am throw an error:

Exception in thread "main" java.lang.ClassCastException:java.util.AbstractMap$SimpleEntry cannot be cast to java.lang.Comparable

Now i don't know how to implement a custom comparator for a TreeSet which sorts my values ascendingly (In Dijkstra's, the edge with least weight would come out first right?). Also, if not possible with TreeSet, could you provide me with a Priority Queue with a comparator implemented?

Even if you didn't follow, Here's my code. Hopefully you'll understand:

EDIT Code Edited as per suggestion from below answer

package GRAPH;

import java.io.*;
import java.util.*;

/**
 * Created by Shreyans on 3/25/2015 at 7:26 PM using IntelliJ IDEA (Fast IO Template)
 */

class DIJKSTA_TRY
{
    public static void main(String[] args) throws Exception
    {
        InputReader in = new InputReader(System.in);
        OutputWriter out = new OutputWriter(System.out);
        //Initializing Graph
        List<ArrayList<AbstractMap.SimpleEntry<Integer,Integer>>>gr=new ArrayList<ArrayList<AbstractMap.SimpleEntry<Integer, Integer>>>();//AbstractMap.SimpleEntry<Integer,Integer> is similar to pair<int a,int b> in C++
        System.out.println("Enter no of Vertices");
        int v=in.readInt();
        System.out.println("Enter no of Edges");
        int e=in.readInt();
        for(int i=0;i<=v;i++)//Initializing rows for each vertex
        {
            gr.add(new ArrayList<AbstractMap.SimpleEntry<Integer, Integer>>());
        }
        System.out.println("Enter <Vertex> <Adjacent Vertex> <Weight>");
        for(int i=0;i<e;i++)
        {
            int a = in.readInt();
            int b = in.readInt();
            int c = in.readInt();
            gr.get(a).add(new AbstractMap.SimpleEntry<Integer, Integer>(b, c));
        }
        out.printLine(gr);
        System.out.printf("Enter Source");
        int s=in.readInt();
        Comparator<AbstractMap.SimpleEntry<Integer, Integer>> comparator=new WeightComparator();
        TreeSet<AbstractMap.SimpleEntry<Integer, Integer>>ts=new TreeSet<AbstractMap.SimpleEntry<Integer, Integer>>(comparator);
        for(AbstractMap.SimpleEntry<Integer, Integer> pair: gr.get(s))//Error:Exception in thread "main" java.lang.ClassCastException: java.util.AbstractMap$SimpleEntry cannot be cast to java.lang.Comparable
        {
            ts.add(pair);
        }
        out.printLine(ts);
        {
            out.close();
        }
    }

    static public class WeightComparator implements
            Comparator<AbstractMap.SimpleEntry<Integer, Integer>>
    {
        @Override
        public int compare(AbstractMap.SimpleEntry<Integer, Integer> one,
                           AbstractMap.SimpleEntry<Integer, Integer> two)
        {
            return Integer.compare(one.getValue(), two.getValue());
        }
    }
    //FAST IO
    private static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                } catch (IOException e)
                {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public double readDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, readInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public long readLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }

    private static class OutputWriter
    {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream)
        {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer)
        {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects)
        {
            for (int i = 0; i < objects.length; i++)
            {
                if (i != 0)
                    writer.print(' ');
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects)
        {
            print(objects);
            writer.println();
        }

        public void close()
        {
            writer.close();
        }

        public void flush()
        {
            writer.flush();
        }
    }
}

Enter Source1
[[], [2=3, 4=3], [3=4], [1=7], [3=2]]
[2=3]

EDIT Works. Thanks @rgettman


回答1:


You received the error because the AbstractMap.SimpleEntry class doesn't implement Comparable. A TreeSet that isn't given a Comparator must assume that its elements are Comparable, but they aren't.

You were right to determine that you need to create a Comparator, to tell the TreeSet how to order the elements.

Create your own class that implements Comparator<AbstractMap.SimpleEntry<Integer, Integer>>. In the compare method, extract the weights and compare them.

public class WeightComparator implements
    Comparator<AbstractMap.SimpleEntry<Integer, Integer>>
{
    @Override
    public int compare(AbstractMap.SimpleEntry<Integer, Integer> one,
                       AbstractMap.SimpleEntry<Integer, Integer> two)
    {
        return Integer.compare(one.getValue(), two.getValue());
    }
}


来源:https://stackoverflow.com/questions/29755369/having-trouble-implementing-a-custom-comparator-for-a-treeset-dijkstras

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!