遇到问题实现自定义比较器TreeSet中(Dijkstra的) [英] Having trouble Implementing a Custom Comparator for a TreeSet (Dijkstra's)

查看:286
本文介绍了遇到问题实现自定义比较器TreeSet中(Dijkstra的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在贯彻Dijkstra的使用邻接表自己的自定义O(N.lgN)解决方案。现在,如果你熟悉这个算法(最有可能你),我遇到了麻烦存储的元组的每个顶点。如果你不知道我在说什么,有alook为: http://qr.ae/LoESY

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

元组可以方便地存储在C ++中使用

Tuples can easily be stored in C++ using

pair <int,int>.

不管怎么说,我发现了一个解决方案,这一点,才知道,排除万难,一个类似的类确实存在其所谓的AbstractMap.SimpleEntry'级。细节在这里给出:

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:

<一个href="http://stackoverflow.com/a/11253710/4258892">http://stackoverflow.com/a/11253710/4258892

现在,您已经阅读它,这个工程几乎一样对&LT;>并足以存储邻边为关键和重量的元组的值

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.

宣言:为Map.Entry对=新AbstractMap.SimpleEntry(1,2);

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

现在我已经存储在一个ArrayList每个向量元组的形式全部投入。我计划将进入到TreeSet中源的元组,并对其进行排序升序排列WRT的权重(是吗?)。但是,如果我只是这些元组添加到TreeSet中,我抛出了一个错误:

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

现在我不知道如何实现自定义比较的TreeSet的这ascendingly排序我的价值观(在Dijkstra的,具有最小权重的边缘会出来第一吧?)。此外,如果无法与TreeSet中,你能为我提供一个优先级队列与实现的比较?

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?

即使你没有遵循,这是我的code。希望你会明白:

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

修改 code编辑根据建议,从下面的答案

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]

修改作品。由于@rgettman

EDIT Works. Thanks @rgettman

推荐答案

您收到错误,因为 AbstractMap.SimpleEntry 类没有实现可比。 A TreeSet的未给出比较必须假设它的元素是可比,但事实并非如此。

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.

您是正确的决定,你需要创建一个比较,告诉 TreeSet的如何订购元素。

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

创建自己的类实现比较&LT; AbstractMap.SimpleEntry&LT;整数,整数GT;&GT; 。在的方法,提取重物,并进行比较。

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());
    }
}

这篇关于遇到问题实现自定义比较器TreeSet中(Dijkstra的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆