EDIT: [решено]Оптимизация для Дейкстры требуется (уникальный алгоритм)
ИМЕЮТ ВЗГЛЯД НА МОЕ ОТВЕТ НА ЭТОЙ СТРАНИЦЕ
Alright так в моем стремлении реализовать O (N.lgN) Решение Дийкстры в JAVA, я понял, что в первую очередь было трудно создать кортежи для смежных вершин и весов для каждой вершины. Это может easiy быть сделано в C++ с использованием:
pair<int adv_vertex,int weight>
Если вы понятия не имеете, о чем я говорю о том, посмотрите на это решение: http://qr.ae/LoESY
Теперь, несмотря на все трудности, я нашел контейнер похож на «пара <>» в JAVA. В качестве примера (1,1), объявленное как:
Map.Entry<Integer, Integer> pair=new AbstractMap.SimpleEntry<Integer,Integer>(1,1);
Читайте подробности здесь: https://stackoverflow.com/a/11253710/4258892
Теперь, мне удалось в реализации алгоритма Дейкстры с использованием этого структура данных. Я использовал TreeSet с пользовательским компаратором. Это в значительной степени работает как PriorityQueue, который извлекает вершины с наименьшим весом в первую очередь. Этот вопрос можно рассматривать как расширенный вариант:
Having trouble Implementing a Custom Comparator for a TreeSet (Dijkstra's)
После Everthing было сделано, я попробовал свои силы на эту проблему:
http://www.spoj.com/problems/EZDIJKST/
Он очищает выборочные testcases, но я получаю предел TLE() TIme Exceeded) при подаче. Так много для реализации Dijkstra, как никто никогда не имел.
Вот код, который получил TLE: http://ideone.com/wAQfBu
И вот моя фактическая реализация Дейкстра с объяснением. Тот, который я представил SPOJ, просто без комментариев и выходных запросов. Это может занять некоторое время, чтобы вы могли опустить голову. Я пробовал комментировать, где и когда это возможно.
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);
//Initializing Graph
//AbstractMap.SimpleEntry<Integer,Integer> is similar to pair<int a,int b> in C++
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();
Set<Integer>vertices=new HashSet<Integer>();
for(int i=0;i<=v;i++)//Initializing rows for each vertex
{
vertices.add(i);
gr.add(new ArrayList<AbstractMap.SimpleEntry<Integer, Integer>>());
}
vertices.remove(0);//Since 0 was added in advertantly
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));
}
System.out.println("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);
int[]d=new int[v+1];
Arrays.fill(d,Integer.MAX_VALUE);//Initial distance INFINITY
d[s]=0;//Setting distance of source from source 0
vertices.remove(s);
for(AbstractMap.SimpleEntry<Integer, Integer> pair:gr.get(s))//Storing vertices adjacent to source
{
ts.add(pair);
d[pair.getKey()]=pair.getValue();
}
while(!vertices.isEmpty()&&!ts.isEmpty())
{
AbstractMap.SimpleEntry<Integer, Integer> curr=ts.pollFirst();//Removing that element
int V=curr.getKey();//Got adjacent vertex;
int W=curr.getValue();//Got weight
//vertices.remove();
for(AbstractMap.SimpleEntry<Integer, Integer> pair:gr.get(V))//Now traversing vertives adjacent to V
{
int v1=pair.getKey();
int w1=pair.getValue();
if(d[v1]>W+w1)//setting distance if shorted
{
d[v1]=W+w1;
}
ts.add(pair);//Adding to TreeSet
}
vertices.remove(V);//Removing V from Vertices set
}
System.out.println("Single Source Shortest Distance from Vertex "+(s)+" is:");
for(int i=1;i<=v;i++)
{
System.out.println("Shortest Distance from Source Vertex "+s+" is: "+d[i]);
}
}
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. THAT'S IT. NOTHING DOWN HERE**
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();
}
}
}
Я был действительно толкнул, когда я закончил кодирование этого. Мне потребовалось почти 5 часов, чтобы найти все ресурсы и собрать их вместе, чтобы сделать это, но был очень разочарован, когда он не мог своевременно очистить пробные места.
Может ли кто-нибудь пожелать предложить другой способ (возможно, структуру данных)/Оптимизация?
Кроме того, каково время работы этого конкретного алгоритма? К чему вы его изменили? (Если у вас есть)
Разве вы не должны решать проблему самостоятельно, так как [spoj.com] (http://www.spoj.com/) - это сайт для решения проблем с рангом и т. Д. ...? – ericbn
Я не прошу ответа на эту проблему. У меня это уже есть. Я спрашиваю вас, как оптимизировать вышеупомянутое решение. ЭТО ЛЕГКО КОДИРОВАНИЕ В СТАНДАРТНОЙ ADJ MATRIX DIJKSTRA. Если вы видите, на каком уровне я закодировал выше, вы не будете сомневаться в моей способности кодировать последнее или о моих знаниях. – bholagabbar
И меня меньше всего интересуют ряды. Я здесь, чтобы узнать – bholagabbar