首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >帮助解决来自SPOJ的算法问题

帮助解决来自SPOJ的算法问题
EN

Stack Overflow用户
提问于 2010-07-11 06:52:09
回答 8查看 2.3K关注 0票数 2

我认为这将是一个有趣的问题:Prime Path

But...It对我来说很难。我唯一的想法是“解决背包问题”..没有其他的想法。你能以好的方式跟踪我吗?这不是为了任何挑战或大学家庭作业。我只是想学点东西。

_

好的,但是首先,如何找到这个质数?我是否需要找到所有4位素数,并将其添加到图中?

现在,我已经生成了所有的质数。

http://pastebin.com/wbhRNRHQ

你能给我在邻居列表上声明图形构建的示例代码吗?

EN

回答 8

Stack Overflow用户

发布于 2010-07-11 06:57:08

看起来像是一个简单的图路径查找问题。

取所有4位素数作为顶点。用边连接两个,如果我们能从一个到另一个的话。

现在给定两个,你需要在我们刚刚形成的图中找到它们之间的最短路径。一个简单的BFS (广度优先搜索)就可以做到这一点。

对于有时间限制的编程竞赛,您甚至可以对每个可能的素数对路径进行硬编码,并使运行时间接近于零!

票数 7
EN

Stack Overflow用户

发布于 2010-07-11 06:58:27

建立一个图,其中所有的节点都是4位素数,并且到处都是弧线两个数字有三位数是共同的。从那里,这是一个基本的图遍历,以找到从一个节点到另一个节点的最低成本路径。

票数 4
EN

Stack Overflow用户

发布于 2016-07-16 11:48:47

我遇到了一个类似的问题,我必须用最少的步数将一个4位素数1033转换为另一个4位素数3739。我能够解决这个问题,它可能不是很有效,但这里是相同的工作代码。

以下代码是用Java编写的

代码语言:javascript
运行
复制
import java.util.*;

public class PrimeNumberProblem {

    public static void main(String... args) {
        System.out.println("Minimum number of steps required for converting 1033 to 3739 are = "
                + getMinSteps(1033, 3739));
    }

    public static int getMinSteps(int a, int b) {
        if (a == b)
            return 0;

        List<Integer> primes = new ArrayList<>();

        // get all the 4 digit prime numbers
        primes = getPrimeNumbers();

        // consists of graph with vertices as all the prime numbers
        Graph graph = addNumbersToGraph(primes);

        // adding edges to the graph vertices
        Graph finalGraph = addWeightToGraph(graph);

        // min number of steps required
        int result = findShortestRoute(finalGraph.getVertex(a), finalGraph.getVertex(b));

        return result;
    }

    private static int findShortestRoute(Vertex source, Vertex dest) {
        if (source.getVertexValue() == dest.getVertexValue())
            return 0;

        // step 1 Initialize the queue. Also Map to store path
        Queue<Vertex> visitedQueue = new LinkedList<>();
        Map<Vertex, Vertex> currentPrevMap = new HashMap<Vertex, Vertex>();

        // step 2 start from visiting S (starting node), and mark it visited, add to queue
        Map<Integer, Boolean> visited = new HashMap<Integer, Boolean>();
        visited.put(source.getVertexValue(), true);
        visitedQueue.add(source);

        int level = 0;
        // step 3 Repeat until queue is empty
        while (!visitedQueue.isEmpty()) {
            // step 4 remove from queue
            Vertex current = visitedQueue.remove();
            if (current.getVertexValue() == dest.getVertexValue()) {
                printPath(source, dest, currentPrevMap);
                return level;
            } else if (current.getAdjacentVertices().size() > 0) {
                level++;
            }
            // step 5 add each of the unvisited neighbour and mark visited
            for (Vertex adjacentVertex : current.getAdjacentVertices()) {
                Integer value = adjacentVertex.getVertexValue();
                if (value == dest.getVertexValue()) {
                    currentPrevMap.put(adjacentVertex, current);
                    printPath(source, dest, currentPrevMap);
                    return level;
                }
                if (visited.get(value) == null) {
                    currentPrevMap.put(adjacentVertex, current);
                    // mark visited and enqueue it
                    visited.put(value, true);
                    visitedQueue.add(adjacentVertex);
                }
            }
        }
        // not found
        System.out.println("Dest vertex not found");
        return -1;
    }

    private static void printPath(Vertex source, Vertex dest, Map<Vertex, Vertex> currentPrevMap) {
        Vertex node = dest;
        System.out.println("Reverse Path from source: " + source.getVertexValue() + " to dest: "
                + dest.getVertexValue());
        while (node != source) {
            System.out.println(node.getVertexValue());
            node = currentPrevMap.get(node);
        }
        System.out.println(source.getVertexValue());
    }

    private static Graph addWeightToGraph(Graph graph) {
        List<Vertex> vertices = graph.getAllVertices();
        for (Vertex i : vertices) {
            for (Vertex j : vertices) {
                if (i.equals(j))
                    continue;

                if (distance(i, j) == 1) {
                    i.getAdjacentVertices().add(j);
                    // i.addEdge(new Edge(i, j, 1));
                }
            }
        }
        return graph;
    }

    private static int distance(Vertex source, Vertex dest) {
        if (source.getVertexValue() == dest.getVertexValue()) {
            return 0;
        }

        char[] numA = extractIntegers(source.getVertexValue());
        char[] numB = extractIntegers(dest.getVertexValue());

        int len1 = numA.length;

        int tracker = 0;

        for (int i = 0; i < len1; i++) {

            if (numA[i] != numB[i]) {
                numA[i] = numB[i];
                tracker++;
                String sA = String.copyValueOf(numA);
                String sB = String.copyValueOf(numB);
                // if we have reached destination
                if (Integer.parseInt(sA) == Integer.parseInt(sB)) {
                    return tracker;
                }
            }

        }
        return tracker;
    }

    private static char[] extractIntegers(int i) {
        char[] arr = Integer.toString(i).toCharArray();
        return arr;
    }

    private static Graph addNumbersToGraph(List<Integer> primes) {
        Graph g = new Graph();
        for (Integer prime : primes) {
            g.addVertex(new Vertex(prime));
        }
        return g;
    }

    private static List<Integer> getPrimeNumbers() {
        List<Integer> fourDigitPrimes = new ArrayList<>();
        fourDigitPrimes.add(1033);
        fourDigitPrimes.add(1733);
        fourDigitPrimes.add(3733);
        fourDigitPrimes.add(3739);

        // for (int i = 1000; i < 9999; i++) {
        // if (isPrime(i))
        // fourDigitPrimes.add(i);
        // }

        return fourDigitPrimes;
    }

    private static boolean isPrime(int i) {

        for (int k = 2; k < Math.sqrt(i); k++) {
            if (i % k == 0)
                return false;
        }

        return true;
    }
}


class Graph {
    public List<Vertex> vertexList = new ArrayList<Vertex>();

    public void addVertex(Vertex V) {
        vertexList.add(V);
    }


    public List getAllAdjacentNodes(Vertex V) {
        return V.getAdjacentVertices();
    }

    public List getAllVertices() {
        return vertexList;
    }

    public Vertex getVertex(int val) {
        Iterator<Vertex> keys = vertexList.iterator();
        while (keys.hasNext()) {
            Vertex v = keys.next();
            if (v.getVertexValue() == val)
                return v;
        }
        return null;
    }
}


class Vertex {
    int value;
    private List<Vertex> adjacentVertices = new ArrayList<Vertex>();

    public Vertex(int v) {
        this.value = v;
    }

    public List<Vertex> getAdjacentVertices() {
        return adjacentVertices;
    }


    public int getVertexValue() {
        return value;
    }


    @Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        Vertex vertex = (Vertex) o;

        return value == vertex.value;

    }

    @Override
    public int hashCode() {
        return value;
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3221134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档