Algorithms: Efficiently find a path containing at least $k$ nodes of some given colors. The Next CEO of Stack OverflowDirected Graph, shortest path algorithm. I don't even understand what this question is asking. Is it a trick question or just Dijkstra's?Finding the longest path in an undirected weighted treeProving Vizing's Theorem using InductionShortest acyclical path between two nodes, negative weights allowedThe graph which has the least edges while satisfying this propertyModified Shortest Path ProblemTest question regarding graph theory - please check my workWeak, Regular, and Strong connectivity in directed graphsQuestion about a proof of “Graph $G$ has no odd cycles $implies$ $G$ is bipartite”Find shortest path in graph that visits 2 nodes from a certain node set

Necessary condition on homology group for a set to be contractible

Example of a Mathematician/Physicist whose Other Publications during their PhD eclipsed their PhD Thesis

A Man With a Stainless Steel Endoskeleton (like The Terminator) Fighting Cloaked Aliens Only He Can See

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

Method for adding error messages to a dictionary given a key

RigExpert AA-35 - Interpreting The Information

Is it convenient to ask the journal's editor for two additional days to complete a review?

Poetry, calligrams and TikZ/PStricks challenge

A small doubt about the dominated convergence theorem

Is French Guiana a (hard) EU border?

How to edit “Name” property in GCI output?

Domestic-to-international connection at Orlando (MCO)

Why do airplanes bank sharply to the right after air-to-air refueling?

Reference request: Grassmannian and Plucker coordinates in type B, C, D

How to prove a simple equation?

Rotate a column

WOW air has ceased operation, can I get my tickets refunded?

What happened in Rome, when the western empire "fell"?

What does "Its cash flow is deeply negative" mean?

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

Is the D&D universe the same as the Forgotten Realms universe?

Easy to read palindrome checker

Newlines in BSD sed vs gsed

When you upcast Blindness/Deafness, do all targets suffer the same effect?



Algorithms: Efficiently find a path containing at least $k$ nodes of some given colors.



The Next CEO of Stack OverflowDirected Graph, shortest path algorithm. I don't even understand what this question is asking. Is it a trick question or just Dijkstra's?Finding the longest path in an undirected weighted treeProving Vizing's Theorem using InductionShortest acyclical path between two nodes, negative weights allowedThe graph which has the least edges while satisfying this propertyModified Shortest Path ProblemTest question regarding graph theory - please check my workWeak, Regular, and Strong connectivity in directed graphsQuestion about a proof of “Graph $G$ has no odd cycles $implies$ $G$ is bipartite”Find shortest path in graph that visits 2 nodes from a certain node set










0












$begingroup$


Suppose you have a directed graph with vertices colored A, B, C, and D. One node is $s$, the start node, and another $t$, the terminal node. You want to determine two things: First, find a path from $s$ to $t$ which contain at least one vertex of colors A, B, and C, and minimize the number of vertices of color D. Paths need not be simple.



Second, for any given $k>0$ determine whether a path exists which visits $k$-many vertices of color A, and $k$-many of color B, and $k$-many of color C. Again paths need not be simple.




Solution to the first part:



For the first question, I used the following solution: If the color at $s$ is A then we look for paths that go to a vertex colored B and then C minimizing the number of vertices colored D. Then we look for paths that go C then B minimizing the vertices colored at D. Then take the minimum of these two results. As long as we can find the minimum path for some specific color ordering in linear time, then doing it twice will still take linear time.



So to do that, first give every edge of the graph which enters a D vertex weight 1 and all others weight 0. Next make three copies of the graph, so that you have G, G', and G''. In G reassign every edge coming from an A vertex to a B to map into the corresponding vertex of G'. Then do likewise mapping B to C edges into the corresponding vertex of G''.



On this new graph run Dijkstra's. Since edges are not negative and bounded by a small constant, the algorithm runs in linear time.



To reiterate, since we can do it in some particular order of colors, we can do it then on all permutations of colors and this only multiplies linear time by a constant, so the algorithm continues to run in constant time.




I think I got the first part right but am a little more hung up on the second. I've imagined trying to leverage the solution to the first part. Perhaps make $k$ copies of the graph, on each copy run the algorithm ... but that doesn't make sense, you couldn't just stitch together two such paths and be ensured that such a path exists in the original graph. I thought maybe I should make $3k$ copies of the graph but I'm not sure how I would bind them together.



Hints or advice would be welcome.










share|cite|improve this question











$endgroup$











  • $begingroup$
    What is asymptotic restriction on complexity of algorithm?
    $endgroup$
    – Vladislav
    Mar 27 at 22:51











  • $begingroup$
    @Vladislav $O(|V|+|E|)$
    $endgroup$
    – Addem
    Mar 27 at 22:52










  • $begingroup$
    Ok, maybe I am not following you but I don't get how your solution is linear. Let's suppose a has color A and T has color C. You want to find shortest (in terms of number of D) path containing B. You can find shortest path from a to any B vertex in linear time, but next you have to iterate all B vertexes (it can be O(V) of them) and find the shortest path from every B to t. So it takes O(V *(V +E)), doesn't it?
    $endgroup$
    – Vladislav
    Mar 27 at 23:07










  • $begingroup$
    @Vladislav So my logic is that I have reproduced the graph three times, therefore there are $3|V|$ vertices and $3|E|$ edges. Since this is linear growth, it's not important. I remap some of the edges and add some weights and run Dijkstra's. Since I'm not finding a path from every B vertex to t then I shouldn't have the time complexity you wrote, but rather $O(3|V|+3|E|) = O(|V|+|E|)$. I can try to describe again the nature of the re-mapping and edge weights if that's still not clear.
    $endgroup$
    – Addem
    Mar 27 at 23:46















0












$begingroup$


Suppose you have a directed graph with vertices colored A, B, C, and D. One node is $s$, the start node, and another $t$, the terminal node. You want to determine two things: First, find a path from $s$ to $t$ which contain at least one vertex of colors A, B, and C, and minimize the number of vertices of color D. Paths need not be simple.



Second, for any given $k>0$ determine whether a path exists which visits $k$-many vertices of color A, and $k$-many of color B, and $k$-many of color C. Again paths need not be simple.




Solution to the first part:



For the first question, I used the following solution: If the color at $s$ is A then we look for paths that go to a vertex colored B and then C minimizing the number of vertices colored D. Then we look for paths that go C then B minimizing the vertices colored at D. Then take the minimum of these two results. As long as we can find the minimum path for some specific color ordering in linear time, then doing it twice will still take linear time.



So to do that, first give every edge of the graph which enters a D vertex weight 1 and all others weight 0. Next make three copies of the graph, so that you have G, G', and G''. In G reassign every edge coming from an A vertex to a B to map into the corresponding vertex of G'. Then do likewise mapping B to C edges into the corresponding vertex of G''.



On this new graph run Dijkstra's. Since edges are not negative and bounded by a small constant, the algorithm runs in linear time.



To reiterate, since we can do it in some particular order of colors, we can do it then on all permutations of colors and this only multiplies linear time by a constant, so the algorithm continues to run in constant time.




I think I got the first part right but am a little more hung up on the second. I've imagined trying to leverage the solution to the first part. Perhaps make $k$ copies of the graph, on each copy run the algorithm ... but that doesn't make sense, you couldn't just stitch together two such paths and be ensured that such a path exists in the original graph. I thought maybe I should make $3k$ copies of the graph but I'm not sure how I would bind them together.



Hints or advice would be welcome.










share|cite|improve this question











$endgroup$











  • $begingroup$
    What is asymptotic restriction on complexity of algorithm?
    $endgroup$
    – Vladislav
    Mar 27 at 22:51











  • $begingroup$
    @Vladislav $O(|V|+|E|)$
    $endgroup$
    – Addem
    Mar 27 at 22:52










  • $begingroup$
    Ok, maybe I am not following you but I don't get how your solution is linear. Let's suppose a has color A and T has color C. You want to find shortest (in terms of number of D) path containing B. You can find shortest path from a to any B vertex in linear time, but next you have to iterate all B vertexes (it can be O(V) of them) and find the shortest path from every B to t. So it takes O(V *(V +E)), doesn't it?
    $endgroup$
    – Vladislav
    Mar 27 at 23:07










  • $begingroup$
    @Vladislav So my logic is that I have reproduced the graph three times, therefore there are $3|V|$ vertices and $3|E|$ edges. Since this is linear growth, it's not important. I remap some of the edges and add some weights and run Dijkstra's. Since I'm not finding a path from every B vertex to t then I shouldn't have the time complexity you wrote, but rather $O(3|V|+3|E|) = O(|V|+|E|)$. I can try to describe again the nature of the re-mapping and edge weights if that's still not clear.
    $endgroup$
    – Addem
    Mar 27 at 23:46













0












0








0


0



$begingroup$


Suppose you have a directed graph with vertices colored A, B, C, and D. One node is $s$, the start node, and another $t$, the terminal node. You want to determine two things: First, find a path from $s$ to $t$ which contain at least one vertex of colors A, B, and C, and minimize the number of vertices of color D. Paths need not be simple.



Second, for any given $k>0$ determine whether a path exists which visits $k$-many vertices of color A, and $k$-many of color B, and $k$-many of color C. Again paths need not be simple.




Solution to the first part:



For the first question, I used the following solution: If the color at $s$ is A then we look for paths that go to a vertex colored B and then C minimizing the number of vertices colored D. Then we look for paths that go C then B minimizing the vertices colored at D. Then take the minimum of these two results. As long as we can find the minimum path for some specific color ordering in linear time, then doing it twice will still take linear time.



So to do that, first give every edge of the graph which enters a D vertex weight 1 and all others weight 0. Next make three copies of the graph, so that you have G, G', and G''. In G reassign every edge coming from an A vertex to a B to map into the corresponding vertex of G'. Then do likewise mapping B to C edges into the corresponding vertex of G''.



On this new graph run Dijkstra's. Since edges are not negative and bounded by a small constant, the algorithm runs in linear time.



To reiterate, since we can do it in some particular order of colors, we can do it then on all permutations of colors and this only multiplies linear time by a constant, so the algorithm continues to run in constant time.




I think I got the first part right but am a little more hung up on the second. I've imagined trying to leverage the solution to the first part. Perhaps make $k$ copies of the graph, on each copy run the algorithm ... but that doesn't make sense, you couldn't just stitch together two such paths and be ensured that such a path exists in the original graph. I thought maybe I should make $3k$ copies of the graph but I'm not sure how I would bind them together.



Hints or advice would be welcome.










share|cite|improve this question











$endgroup$




Suppose you have a directed graph with vertices colored A, B, C, and D. One node is $s$, the start node, and another $t$, the terminal node. You want to determine two things: First, find a path from $s$ to $t$ which contain at least one vertex of colors A, B, and C, and minimize the number of vertices of color D. Paths need not be simple.



Second, for any given $k>0$ determine whether a path exists which visits $k$-many vertices of color A, and $k$-many of color B, and $k$-many of color C. Again paths need not be simple.




Solution to the first part:



For the first question, I used the following solution: If the color at $s$ is A then we look for paths that go to a vertex colored B and then C minimizing the number of vertices colored D. Then we look for paths that go C then B minimizing the vertices colored at D. Then take the minimum of these two results. As long as we can find the minimum path for some specific color ordering in linear time, then doing it twice will still take linear time.



So to do that, first give every edge of the graph which enters a D vertex weight 1 and all others weight 0. Next make three copies of the graph, so that you have G, G', and G''. In G reassign every edge coming from an A vertex to a B to map into the corresponding vertex of G'. Then do likewise mapping B to C edges into the corresponding vertex of G''.



On this new graph run Dijkstra's. Since edges are not negative and bounded by a small constant, the algorithm runs in linear time.



To reiterate, since we can do it in some particular order of colors, we can do it then on all permutations of colors and this only multiplies linear time by a constant, so the algorithm continues to run in constant time.




I think I got the first part right but am a little more hung up on the second. I've imagined trying to leverage the solution to the first part. Perhaps make $k$ copies of the graph, on each copy run the algorithm ... but that doesn't make sense, you couldn't just stitch together two such paths and be ensured that such a path exists in the original graph. I thought maybe I should make $3k$ copies of the graph but I'm not sure how I would bind them together.



Hints or advice would be welcome.







graph-theory algorithms






share|cite|improve this question















share|cite|improve this question













share|cite|improve this question




share|cite|improve this question








edited Mar 27 at 20:50







Addem

















asked Mar 27 at 19:32









AddemAddem

1,7441429




1,7441429











  • $begingroup$
    What is asymptotic restriction on complexity of algorithm?
    $endgroup$
    – Vladislav
    Mar 27 at 22:51











  • $begingroup$
    @Vladislav $O(|V|+|E|)$
    $endgroup$
    – Addem
    Mar 27 at 22:52










  • $begingroup$
    Ok, maybe I am not following you but I don't get how your solution is linear. Let's suppose a has color A and T has color C. You want to find shortest (in terms of number of D) path containing B. You can find shortest path from a to any B vertex in linear time, but next you have to iterate all B vertexes (it can be O(V) of them) and find the shortest path from every B to t. So it takes O(V *(V +E)), doesn't it?
    $endgroup$
    – Vladislav
    Mar 27 at 23:07










  • $begingroup$
    @Vladislav So my logic is that I have reproduced the graph three times, therefore there are $3|V|$ vertices and $3|E|$ edges. Since this is linear growth, it's not important. I remap some of the edges and add some weights and run Dijkstra's. Since I'm not finding a path from every B vertex to t then I shouldn't have the time complexity you wrote, but rather $O(3|V|+3|E|) = O(|V|+|E|)$. I can try to describe again the nature of the re-mapping and edge weights if that's still not clear.
    $endgroup$
    – Addem
    Mar 27 at 23:46
















  • $begingroup$
    What is asymptotic restriction on complexity of algorithm?
    $endgroup$
    – Vladislav
    Mar 27 at 22:51











  • $begingroup$
    @Vladislav $O(|V|+|E|)$
    $endgroup$
    – Addem
    Mar 27 at 22:52










  • $begingroup$
    Ok, maybe I am not following you but I don't get how your solution is linear. Let's suppose a has color A and T has color C. You want to find shortest (in terms of number of D) path containing B. You can find shortest path from a to any B vertex in linear time, but next you have to iterate all B vertexes (it can be O(V) of them) and find the shortest path from every B to t. So it takes O(V *(V +E)), doesn't it?
    $endgroup$
    – Vladislav
    Mar 27 at 23:07










  • $begingroup$
    @Vladislav So my logic is that I have reproduced the graph three times, therefore there are $3|V|$ vertices and $3|E|$ edges. Since this is linear growth, it's not important. I remap some of the edges and add some weights and run Dijkstra's. Since I'm not finding a path from every B vertex to t then I shouldn't have the time complexity you wrote, but rather $O(3|V|+3|E|) = O(|V|+|E|)$. I can try to describe again the nature of the re-mapping and edge weights if that's still not clear.
    $endgroup$
    – Addem
    Mar 27 at 23:46















$begingroup$
What is asymptotic restriction on complexity of algorithm?
$endgroup$
– Vladislav
Mar 27 at 22:51





$begingroup$
What is asymptotic restriction on complexity of algorithm?
$endgroup$
– Vladislav
Mar 27 at 22:51













$begingroup$
@Vladislav $O(|V|+|E|)$
$endgroup$
– Addem
Mar 27 at 22:52




$begingroup$
@Vladislav $O(|V|+|E|)$
$endgroup$
– Addem
Mar 27 at 22:52












$begingroup$
Ok, maybe I am not following you but I don't get how your solution is linear. Let's suppose a has color A and T has color C. You want to find shortest (in terms of number of D) path containing B. You can find shortest path from a to any B vertex in linear time, but next you have to iterate all B vertexes (it can be O(V) of them) and find the shortest path from every B to t. So it takes O(V *(V +E)), doesn't it?
$endgroup$
– Vladislav
Mar 27 at 23:07




$begingroup$
Ok, maybe I am not following you but I don't get how your solution is linear. Let's suppose a has color A and T has color C. You want to find shortest (in terms of number of D) path containing B. You can find shortest path from a to any B vertex in linear time, but next you have to iterate all B vertexes (it can be O(V) of them) and find the shortest path from every B to t. So it takes O(V *(V +E)), doesn't it?
$endgroup$
– Vladislav
Mar 27 at 23:07












$begingroup$
@Vladislav So my logic is that I have reproduced the graph three times, therefore there are $3|V|$ vertices and $3|E|$ edges. Since this is linear growth, it's not important. I remap some of the edges and add some weights and run Dijkstra's. Since I'm not finding a path from every B vertex to t then I shouldn't have the time complexity you wrote, but rather $O(3|V|+3|E|) = O(|V|+|E|)$. I can try to describe again the nature of the re-mapping and edge weights if that's still not clear.
$endgroup$
– Addem
Mar 27 at 23:46




$begingroup$
@Vladislav So my logic is that I have reproduced the graph three times, therefore there are $3|V|$ vertices and $3|E|$ edges. Since this is linear growth, it's not important. I remap some of the edges and add some weights and run Dijkstra's. Since I'm not finding a path from every B vertex to t then I shouldn't have the time complexity you wrote, but rather $O(3|V|+3|E|) = O(|V|+|E|)$. I can try to describe again the nature of the re-mapping and edge weights if that's still not clear.
$endgroup$
– Addem
Mar 27 at 23:46










1 Answer
1






active

oldest

votes


















0












$begingroup$

I don't think I understood your solution, but I can provide an easy one for the first.



Let's build a new graph $G'=(V', E')$ where $V' = v in V$



In other words, vertexes of $G'$ are pairs of an original vertex and bitmask of visited colors. For instance, $(3, 011)$ means vertex $3$ of $G$ and $A$ has not been visited, $B$ and $C$ has been visited).



$E'$ contains an edge $(v, mask1) rightarrow(u, mask2)$ iff the original graph has the edge $u rightarrow v$ and $mask2$ is $mask1$ with the bit corresponding to color of $u$ set to $1$.



Clearly, all you left to do is to find the shortest path (in terms of number of $D$'s) from $(s, 100)$ (if $s$ has color $A$, if $s$ has color $B$ it will be $010$ and so on) to $(t, 111)$.



Clearly, this new graph has $8|V|$ vertexes and $8|E|$ edges, so it linearly depends on the size of the original one.



On minimization the number of $D$'s: it is a good idea to set edge's weight $0$ or $1$ but it is kind of overkill to run Dijkstra on this graph. In order to find the shortest path on $0,1$ graph you just need to slightly modify breadth-first search. If you explore $1$-weighted edge you add the vertex in the end of the queue (as usual in breadth-first search), but to the beginning of queue if you explore $0$-weighted edge. This algorithm will give us the shortest path.



Unfortunately, this algorithm can not be generalized for an arbitrary $k$ with linear complexity as $G'$ will have $k^3|V|$ vertexes.






share|cite|improve this answer











$endgroup$












  • $begingroup$
    I'm not certain whether I need to treat $k$ as a variable for the growth of the algorithm or not. I've been assuming that I only need to treat it as a fixed parameter. Otherwise, I am pretty skeptical anything could be linear with a growing $k$.
    $endgroup$
    – Addem
    Mar 27 at 23:48










  • $begingroup$
    In this case, you've got a linear solution for an arbitrarily fixed k.
    $endgroup$
    – Vladislav
    Mar 27 at 23:50












Your Answer





StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["$", "$"], ["\\(","\\)"]]);
);
);
, "mathjax-editing");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "69"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
noCode: true, onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmath.stackexchange.com%2fquestions%2f3165007%2falgorithms-efficiently-find-a-path-containing-at-least-k-nodes-of-some-given%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0












$begingroup$

I don't think I understood your solution, but I can provide an easy one for the first.



Let's build a new graph $G'=(V', E')$ where $V' = v in V$



In other words, vertexes of $G'$ are pairs of an original vertex and bitmask of visited colors. For instance, $(3, 011)$ means vertex $3$ of $G$ and $A$ has not been visited, $B$ and $C$ has been visited).



$E'$ contains an edge $(v, mask1) rightarrow(u, mask2)$ iff the original graph has the edge $u rightarrow v$ and $mask2$ is $mask1$ with the bit corresponding to color of $u$ set to $1$.



Clearly, all you left to do is to find the shortest path (in terms of number of $D$'s) from $(s, 100)$ (if $s$ has color $A$, if $s$ has color $B$ it will be $010$ and so on) to $(t, 111)$.



Clearly, this new graph has $8|V|$ vertexes and $8|E|$ edges, so it linearly depends on the size of the original one.



On minimization the number of $D$'s: it is a good idea to set edge's weight $0$ or $1$ but it is kind of overkill to run Dijkstra on this graph. In order to find the shortest path on $0,1$ graph you just need to slightly modify breadth-first search. If you explore $1$-weighted edge you add the vertex in the end of the queue (as usual in breadth-first search), but to the beginning of queue if you explore $0$-weighted edge. This algorithm will give us the shortest path.



Unfortunately, this algorithm can not be generalized for an arbitrary $k$ with linear complexity as $G'$ will have $k^3|V|$ vertexes.






share|cite|improve this answer











$endgroup$












  • $begingroup$
    I'm not certain whether I need to treat $k$ as a variable for the growth of the algorithm or not. I've been assuming that I only need to treat it as a fixed parameter. Otherwise, I am pretty skeptical anything could be linear with a growing $k$.
    $endgroup$
    – Addem
    Mar 27 at 23:48










  • $begingroup$
    In this case, you've got a linear solution for an arbitrarily fixed k.
    $endgroup$
    – Vladislav
    Mar 27 at 23:50
















0












$begingroup$

I don't think I understood your solution, but I can provide an easy one for the first.



Let's build a new graph $G'=(V', E')$ where $V' = v in V$



In other words, vertexes of $G'$ are pairs of an original vertex and bitmask of visited colors. For instance, $(3, 011)$ means vertex $3$ of $G$ and $A$ has not been visited, $B$ and $C$ has been visited).



$E'$ contains an edge $(v, mask1) rightarrow(u, mask2)$ iff the original graph has the edge $u rightarrow v$ and $mask2$ is $mask1$ with the bit corresponding to color of $u$ set to $1$.



Clearly, all you left to do is to find the shortest path (in terms of number of $D$'s) from $(s, 100)$ (if $s$ has color $A$, if $s$ has color $B$ it will be $010$ and so on) to $(t, 111)$.



Clearly, this new graph has $8|V|$ vertexes and $8|E|$ edges, so it linearly depends on the size of the original one.



On minimization the number of $D$'s: it is a good idea to set edge's weight $0$ or $1$ but it is kind of overkill to run Dijkstra on this graph. In order to find the shortest path on $0,1$ graph you just need to slightly modify breadth-first search. If you explore $1$-weighted edge you add the vertex in the end of the queue (as usual in breadth-first search), but to the beginning of queue if you explore $0$-weighted edge. This algorithm will give us the shortest path.



Unfortunately, this algorithm can not be generalized for an arbitrary $k$ with linear complexity as $G'$ will have $k^3|V|$ vertexes.






share|cite|improve this answer











$endgroup$












  • $begingroup$
    I'm not certain whether I need to treat $k$ as a variable for the growth of the algorithm or not. I've been assuming that I only need to treat it as a fixed parameter. Otherwise, I am pretty skeptical anything could be linear with a growing $k$.
    $endgroup$
    – Addem
    Mar 27 at 23:48










  • $begingroup$
    In this case, you've got a linear solution for an arbitrarily fixed k.
    $endgroup$
    – Vladislav
    Mar 27 at 23:50














0












0








0





$begingroup$

I don't think I understood your solution, but I can provide an easy one for the first.



Let's build a new graph $G'=(V', E')$ where $V' = v in V$



In other words, vertexes of $G'$ are pairs of an original vertex and bitmask of visited colors. For instance, $(3, 011)$ means vertex $3$ of $G$ and $A$ has not been visited, $B$ and $C$ has been visited).



$E'$ contains an edge $(v, mask1) rightarrow(u, mask2)$ iff the original graph has the edge $u rightarrow v$ and $mask2$ is $mask1$ with the bit corresponding to color of $u$ set to $1$.



Clearly, all you left to do is to find the shortest path (in terms of number of $D$'s) from $(s, 100)$ (if $s$ has color $A$, if $s$ has color $B$ it will be $010$ and so on) to $(t, 111)$.



Clearly, this new graph has $8|V|$ vertexes and $8|E|$ edges, so it linearly depends on the size of the original one.



On minimization the number of $D$'s: it is a good idea to set edge's weight $0$ or $1$ but it is kind of overkill to run Dijkstra on this graph. In order to find the shortest path on $0,1$ graph you just need to slightly modify breadth-first search. If you explore $1$-weighted edge you add the vertex in the end of the queue (as usual in breadth-first search), but to the beginning of queue if you explore $0$-weighted edge. This algorithm will give us the shortest path.



Unfortunately, this algorithm can not be generalized for an arbitrary $k$ with linear complexity as $G'$ will have $k^3|V|$ vertexes.






share|cite|improve this answer











$endgroup$



I don't think I understood your solution, but I can provide an easy one for the first.



Let's build a new graph $G'=(V', E')$ where $V' = v in V$



In other words, vertexes of $G'$ are pairs of an original vertex and bitmask of visited colors. For instance, $(3, 011)$ means vertex $3$ of $G$ and $A$ has not been visited, $B$ and $C$ has been visited).



$E'$ contains an edge $(v, mask1) rightarrow(u, mask2)$ iff the original graph has the edge $u rightarrow v$ and $mask2$ is $mask1$ with the bit corresponding to color of $u$ set to $1$.



Clearly, all you left to do is to find the shortest path (in terms of number of $D$'s) from $(s, 100)$ (if $s$ has color $A$, if $s$ has color $B$ it will be $010$ and so on) to $(t, 111)$.



Clearly, this new graph has $8|V|$ vertexes and $8|E|$ edges, so it linearly depends on the size of the original one.



On minimization the number of $D$'s: it is a good idea to set edge's weight $0$ or $1$ but it is kind of overkill to run Dijkstra on this graph. In order to find the shortest path on $0,1$ graph you just need to slightly modify breadth-first search. If you explore $1$-weighted edge you add the vertex in the end of the queue (as usual in breadth-first search), but to the beginning of queue if you explore $0$-weighted edge. This algorithm will give us the shortest path.



Unfortunately, this algorithm can not be generalized for an arbitrary $k$ with linear complexity as $G'$ will have $k^3|V|$ vertexes.







share|cite|improve this answer














share|cite|improve this answer



share|cite|improve this answer








edited 2 days ago

























answered Mar 27 at 23:43









VladislavVladislav

1015




1015











  • $begingroup$
    I'm not certain whether I need to treat $k$ as a variable for the growth of the algorithm or not. I've been assuming that I only need to treat it as a fixed parameter. Otherwise, I am pretty skeptical anything could be linear with a growing $k$.
    $endgroup$
    – Addem
    Mar 27 at 23:48










  • $begingroup$
    In this case, you've got a linear solution for an arbitrarily fixed k.
    $endgroup$
    – Vladislav
    Mar 27 at 23:50

















  • $begingroup$
    I'm not certain whether I need to treat $k$ as a variable for the growth of the algorithm or not. I've been assuming that I only need to treat it as a fixed parameter. Otherwise, I am pretty skeptical anything could be linear with a growing $k$.
    $endgroup$
    – Addem
    Mar 27 at 23:48










  • $begingroup$
    In this case, you've got a linear solution for an arbitrarily fixed k.
    $endgroup$
    – Vladislav
    Mar 27 at 23:50
















$begingroup$
I'm not certain whether I need to treat $k$ as a variable for the growth of the algorithm or not. I've been assuming that I only need to treat it as a fixed parameter. Otherwise, I am pretty skeptical anything could be linear with a growing $k$.
$endgroup$
– Addem
Mar 27 at 23:48




$begingroup$
I'm not certain whether I need to treat $k$ as a variable for the growth of the algorithm or not. I've been assuming that I only need to treat it as a fixed parameter. Otherwise, I am pretty skeptical anything could be linear with a growing $k$.
$endgroup$
– Addem
Mar 27 at 23:48












$begingroup$
In this case, you've got a linear solution for an arbitrarily fixed k.
$endgroup$
– Vladislav
Mar 27 at 23:50





$begingroup$
In this case, you've got a linear solution for an arbitrarily fixed k.
$endgroup$
– Vladislav
Mar 27 at 23:50


















draft saved

draft discarded
















































Thanks for contributing an answer to Mathematics Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmath.stackexchange.com%2fquestions%2f3165007%2falgorithms-efficiently-find-a-path-containing-at-least-k-nodes-of-some-given%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Boston (Lincolnshire) Stedsbyld | Berne yn Boston | NavigaasjemenuBoston Borough CouncilBoston, Lincolnshire

Ballerup Komuun Stääden an saarpen | Futnuuten | Luke uk diar | Nawigatsjuunwww.ballerup.dkwww.statistikbanken.dk: Tabelle BEF44 (Folketal pr. 1. januar fordelt på byer)Commonskategorii: Ballerup Komuun55° 44′ N, 12° 22′ O

Serbia Índice Etimología Historia Geografía Entorno natural División administrativa Política Demografía Economía Cultura Deportes Véase también Notas Referencias Bibliografía Enlaces externos Menú de navegación44°49′00″N 20°28′00″E / 44.816666666667, 20.46666666666744°49′00″N 20°28′00″E / 44.816666666667, 20.466666666667U.S. Department of Commerce (2015)«Informe sobre Desarrollo Humano 2018»Kosovo-Metohija.Neutralna Srbija u NATO okruzenju.The SerbsTheories on the Origin of the Serbs.Serbia.Earls: Webster's Quotations, Facts and Phrases.Egeo y Balcanes.Kalemegdan.Southern Pannonia during the age of the Great Migrations.Culture in Serbia.History.The Serbian Origin of the Montenegrins.Nemanjics' period (1186-1353).Stefan Uros (1355-1371).Serbian medieval history.Habsburg–Ottoman Wars (1525–1718).The Ottoman Empire, 1700-1922.The First Serbian Uprising.Miloš, prince of Serbia.3. Bosnia-Hercegovina and the Congress of Berlin.The Balkan Wars and the Partition of Macedonia.The Falcon and the Eagle: Montenegro and Austria-Hungary, 1908-1914.Typhus fever on the eastern front in World War I.Anniversary of WWI battle marked in Serbia.La derrota austriaca en los Balcanes. Fin del Imperio Austro-Húngaro.Imperio austriaco y Reino de Hungría.Los tiempos modernos: del capitalismo a la globalización, siglos XVII al XXI.The period of Croatia within ex-Yugoslavia.Yugoslavia: Much in a Name.Las dictaduras europeas.Croacia: mito y realidad."Crods ask arms".Prólogo a la invasión.La campaña de los Balcanes.La resistencia en Yugoslavia.Jasenovac Research Institute.Día en memoria de las víctimas del genocidio en la Segunda Guerra Mundial.El infierno estuvo en Jasenovac.Croacia empieza a «desenterrar» a sus muertos de Jasenovac.World fascism: a historical encyclopedia, Volumen 1.Tito. Josip Broz.El nuevo orden y la resistencia.La conquista del poder.Algunos aspectos de la economía yugoslava a mediados de 1962.Albania-Kosovo crisis.De Kosovo a Kosova: una visión demográfica.La crisis de la economía yugoslava y la política de "estabilización".Milosevic: el poder de un absolutista."Serbia under Milošević: politics in the 1990s"Milosevic cavó en Kosovo la tumba de la antigua Yugoslavia.La ONU exculpa a Serbia de genocidio en la guerra de Bosnia.Slobodan Milosevic, el burócrata que supo usar el odio.Es la fuerza contra el sufrimiento de muchos inocentes.Matanza de civiles al bombardear la OTAN un puente mientras pasaba un tren.Las consecuencias negativas de los bombardeos de Yugoslavia se sentirán aún durante largo tiempo.Kostunica advierte que la misión de Europa en Kosovo es ilegal.Las 24 horas más largas en la vida de Slobodan Milosevic.Serbia declara la guerra a la mafia por matar a Djindjic.Tadic presentará "quizás en diciembre" la solicitud de entrada en la UE.Montenegro declara su independencia de Serbia.Serbia se declara estado soberano tras separación de Montenegro.«Accordance with International Law of the Unilateral Declaration of Independence by the Provisional Institutions of Self-Government of Kosovo (Request for Advisory Opinion)»Mladic pasa por el médico antes de la audiencia para extraditarloDatos de Serbia y Kosovo.The Carpathian Mountains.Position, Relief, Climate.Transport.Finding birds in Serbia.U Srbiji do 2010. godine 10% teritorije nacionalni parkovi.Geography.Serbia: Climate.Variability of Climate In Serbia In The Second Half of The 20thc Entury.BASIC CLIMATE CHARACTERISTICS FOR THE TERRITORY OF SERBIA.Fauna y flora: Serbia.Serbia and Montenegro.Información general sobre Serbia.Republic of Serbia Environmental Protection Agency (SEPA).Serbia recycling 15% of waste.Reform process of the Serbian energy sector.20-MW Wind Project Being Developed in Serbia.Las Naciones Unidas. Paz para Kosovo.Aniversario sin fiesta.Population by national or ethnic groups by Census 2002.Article 7. Coat of arms, flag and national anthem.Serbia, flag of.Historia.«Serbia and Montenegro in Pictures»Serbia.Serbia aprueba su nueva Constitución con un apoyo de más del 50%.Serbia. Population.«El nacionalista Nikolic gana las elecciones presidenciales en Serbia»El europeísta Borís Tadic gana la segunda vuelta de las presidenciales serbias.Aleksandar Vucic, de ultranacionalista serbio a fervoroso europeístaKostunica condena la declaración del "falso estado" de Kosovo.Comienza el debate sobre la independencia de Kosovo en el TIJ.La Corte Internacional de Justicia dice que Kosovo no violó el derecho internacional al declarar su independenciaKosovo: Enviado de la ONU advierte tensiones y fragilidad.«Bruselas recomienda negociar la adhesión de Serbia tras el acuerdo sobre Kosovo»Monografía de Serbia.Bez smanjivanja Vojske Srbije.Military statistics Serbia and Montenegro.Šutanovac: Vojni budžet za 2009. godinu 70 milijardi dinara.Serbia-Montenegro shortens obligatory military service to six months.No hay justicia para las víctimas de los bombardeos de la OTAN.Zapatero reitera la negativa de España a reconocer la independencia de Kosovo.Anniversary of the signing of the Stabilisation and Association Agreement.Detenido en Serbia Radovan Karadzic, el criminal de guerra más buscado de Europa."Serbia presentará su candidatura de acceso a la UE antes de fin de año".Serbia solicita la adhesión a la UE.Detenido el exgeneral serbobosnio Ratko Mladic, principal acusado del genocidio en los Balcanes«Lista de todos los Estados Miembros de las Naciones Unidas que son parte o signatarios en los diversos instrumentos de derechos humanos de las Naciones Unidas»versión pdfProtocolo Facultativo de la Convención sobre la Eliminación de todas las Formas de Discriminación contra la MujerConvención contra la tortura y otros tratos o penas crueles, inhumanos o degradantesversión pdfProtocolo Facultativo de la Convención sobre los Derechos de las Personas con DiscapacidadEl ACNUR recibe con beneplácito el envío de tropas de la OTAN a Kosovo y se prepara ante una posible llegada de refugiados a Serbia.Kosovo.- El jefe de la Minuk denuncia que los serbios boicotearon las legislativas por 'presiones'.Bosnia and Herzegovina. Population.Datos básicos de Montenegro, historia y evolución política.Serbia y Montenegro. Indicador: Tasa global de fecundidad (por 1000 habitantes).Serbia y Montenegro. Indicador: Tasa bruta de mortalidad (por 1000 habitantes).Population.Falleció el patriarca de la Iglesia Ortodoxa serbia.Atacan en Kosovo autobuses con peregrinos tras la investidura del patriarca serbio IrinejSerbian in Hungary.Tasas de cambio."Kosovo es de todos sus ciudadanos".Report for Serbia.Country groups by income.GROSS DOMESTIC PRODUCT (GDP) OF THE REPUBLIC OF SERBIA 1997–2007.Economic Trends in the Republic of Serbia 2006.National Accounts Statitics.Саопштења за јавност.GDP per inhabitant varied by one to six across the EU27 Member States.Un pacto de estabilidad para Serbia.Unemployment rate rises in Serbia.Serbia, Belarus agree free trade to woo investors.Serbia, Turkey call investors to Serbia.Success Stories.U.S. Private Investment in Serbia and Montenegro.Positive trend.Banks in Serbia.La Cámara de Comercio acompaña a empresas madrileñas a Serbia y Croacia.Serbia Industries.Energy and mining.Agriculture.Late crops, fruit and grapes output, 2008.Rebranding Serbia: A Hobby Shortly to Become a Full-Time Job.Final data on livestock statistics, 2008.Serbian cell-phone users.U Srbiji sve više računara.Телекомуникације.U Srbiji 27 odsto gradjana koristi Internet.Serbia and Montenegro.Тренд гледаности програма РТС-а у 2008. и 2009.години.Serbian railways.General Terms.El mercado del transporte aéreo en Serbia.Statistics.Vehículos de motor registrados.Planes ambiciosos para el transporte fluvial.Turismo.Turistički promet u Republici Srbiji u periodu januar-novembar 2007. godine.Your Guide to Culture.Novi Sad - city of culture.Nis - european crossroads.Serbia. Properties inscribed on the World Heritage List .Stari Ras and Sopoćani.Studenica Monastery.Medieval Monuments in Kosovo.Gamzigrad-Romuliana, Palace of Galerius.Skiing and snowboarding in Kopaonik.Tara.New7Wonders of Nature Finalists.Pilgrimage of Saint Sava.Exit Festival: Best european festival.Banje u Srbiji.«The Encyclopedia of world history»Culture.Centenario del arte serbio.«Djordje Andrejevic Kun: el único pintor de los brigadistas yugoslavos de la guerra civil española»About the museum.The collections.Miroslav Gospel – Manuscript from 1180.Historicity in the Serbo-Croatian Heroic Epic.Culture and Sport.Conversación con el rector del Seminario San Sava.'Reina Margot' funde drama, historia y gesto con música de Goran Bregovic.Serbia gana Eurovisión y España decepciona de nuevo con un vigésimo puesto.Home.Story.Emir Kusturica.Tercer oro para Paskaljevic.Nikola Tesla Year.Home.Tesla, un genio tomado por loco.Aniversario de la muerte de Nikola Tesla.El Museo Nikola Tesla en Belgrado.El inventor del mundo actual.República de Serbia.University of Belgrade official statistics.University of Novi Sad.University of Kragujevac.University of Nis.Comida. Cocina serbia.Cooking.Montenegro se convertirá en el miembro 204 del movimiento olímpico.España, campeona de Europa de baloncesto.El Partizan de Belgrado se corona campeón por octava vez consecutiva.Serbia se clasifica para el Mundial de 2010 de Sudáfrica.Serbia Name Squad For Northern Ireland And South Korea Tests.Fútbol.- El Partizán de Belgrado se proclama campeón de la Liga serbia.Clasificacion final Mundial de balonmano Croacia 2009.Serbia vence a España y se consagra campeón mundial de waterpolo.Novak Djokovic no convence pero gana en Australia.Gana Ana Ivanovic el Roland Garros.Serena Williams gana el US Open por tercera vez.Biography.Bradt Travel Guide SerbiaThe Encyclopedia of World War IGobierno de SerbiaPortal del Gobierno de SerbiaPresidencia de SerbiaAsamblea Nacional SerbiaMinisterio de Asuntos exteriores de SerbiaBanco Nacional de SerbiaAgencia Serbia para la Promoción de la Inversión y la ExportaciónOficina de Estadísticas de SerbiaCIA. Factbook 2008Organización nacional de turismo de SerbiaDiscover SerbiaConoce SerbiaNoticias de SerbiaSerbiaWorldCat1512028760000 0000 9526 67094054598-2n8519591900570825ge1309191004530741010url17413117006669D055771Serbia