Storing vertices in Java - Mapping Edges - java

I'm trying to build a graph with vertices, A, B, C & D. The graph must map an edge to a particular vertex if there is an overlap, For instance vertices A and C overlap as A has 1 -> 2, and C has 1 -> 4.
What would be an efficient way of storing these vertices then checking if their values overlap with one another?
Example:
A 1 2 3 4
B 9 10 12 13
C 1 4 2 3
D 15 16 17 18

It depends how often these graphs are expected to change. If it's just once off, storing the vertex constraint in a Map<Vertex, Set<Constraint>, calculating the intersections and then storing the final graph as an adjacency list or matrix is just fine.
You would do something like
For each vertex v:
For each other vertex u
if constraints(u) intersect constraints(v)
add edge between u and v
You will end up with a symmetric un-directed graph.

Related

Finding number of pairs of vertices in a graph such that the path between them has only one vertex common with a different given path

Given a tree with N vertices and N-1 undirected edges.
1<=N<=250000
There are certain queries to be performed.
1<=Q<=10^5
In each query we will be given two vertices,say a and b.
We have to tell the number of pairs of vertices such that the path between those contain exactly one vertex common with the vertices present in the path between the vertices a and b.
For example:
N=6.So N-1 edges.-->
1 2,
1 3,
1 4,
2 5,
2 6.
(Meaning 1 is connected to 2,3,4 and 2 is connected to 1,5,6)
Let our query be a and b--> 4 5.
Answer will be 6.(Means there exist 6 pairs of vertices in the graph with the given condition)
Those 6 pairs are:
1 1,
2 2,
4 4,
5 5,
1 3,
2 6.
I have been thinking this question for 2 days but I am not able to get any perfect logic for this.
I first thought that we can find by using LCA (lowest common ancestor) but then I could not find how.
Please help me to get some of the logic so I can solve it efficiently.

Determining best start and end points for line segment on polygon

I'm having trouble figuring out the best way to solve the following problem. I've tried out multiple methods of solving them but I'm always running into some corner cases.
The problem is the following:
You have a List of coordinates (x and y points) forming a closed polygon. This list is guaranteed to form a polygon with points ordered in a clockwise direction.
You are given a Set of coordinates (x and y points) which are from the above List of coordinates.
You must figure out the start and end points of the line formed using all points in the above Set.
The issue I'm having is that I can't figure out the method of finding the 'best' start and end points. For many scenarios, you can pick the first and last point (using the indices of the List) to form the start and end points, however this could result in a line which is longer than it has to be.
For example, let's say we have the following polygon:
0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 0
And the following Set of coordinates our line segment must contain: 0, 7, 3.
If we find the min and max indices, we get index(0), index(7), so we can form the line 0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7, which is a valid line but it is longer than it needs to be. The best line segment would be 7 -> 0 -> 1 -> 2 -> 3.
How can I find the best (shortest which contains all points in Set) line segment in an efficient manner?
For context: I'm working on an application which using JTS Geometries to draw shapes. The drawn shapes are smoothed using Bezier curves to result in 'curved edges'. After drawing the shapes (by dropping points), users can edit the shape. We want to figure out the start and end points using the points they modify (forms the Set above) so we can 'smooth' only the affected area.
Transform your set into sorted list, concatenate this list with it's copy, where every element is added with number of polygon vertices N, then find the longest empty run (neighbor difference) in this doubled list. Then get sublist of needed length, transform it to continuous range (but take elements modulo N)
(0,3,7) + (0+8,3+8,7+8) = (0,3,7,8,11,15)
max difference is 7-3, so the best case sublist starts with 7, it is
(7%8 .. 11%8) = (7,0,1,2,3)
so we have a Set and we nead to walk this set in the order of the index into List.
convert ISet = [Index(i, List) for i in Set]
next sort ISet
for pairs of consecutive items in ISet and the pair (last, first) compute the distances for that pair.
fined the pair with the max distances. Then the best end and start are that pair.

Finding a Minimum Spanning Tree from an Adjacency List where the Adjacency List is in a string array using Prims Algorithm

So I need some help coming up with a way to find a Minimum spanning tree.
Suppose I have my graph in the form of an adjacency list:
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
The first letter tells which node you are looking at, and the number tells how many connections to any other node there are. For example, A has two connections - one each to B and I. After that, the number that follows the letters simply tell the weight of an edge. B has weight 12 and I has weight 25. So I had originally planned to represent this entire thing as a String array
called Graph[8]. Each line would be a different slot in the array. I am having difficulties figuring out how to accomplish this with either Prims or Kruskalls algorithm.
This isn't a direct answer to your question per-say (seems like you're doing schoolwork), but I think it will help you get started. Why not create a data structure that more closely matches your mental model and build up from there?
class GraphNode {
final String name;
final List<GraphEdge> adjacentNodes;
public GraphNode(String name) {
this.name = name;
adjacentNodes = new ArrayList<GraphEdge>();
}
public void addAdjacency(GraphNode node, int weight) {
adjacentNodes.add(new GraphEdge(node, weight));
}
}
class GraphEdge {
final GraphNode node;
final int weight;
public GraphEdge(GraphEdge node, int weight) {
this.node = node;
this.weight = weight;
}
}
Suppose I have my tree in the form of an adjacency list
It is important (for your understanding) to note that you have a connected graph in this kind of an adjacency list, but I think it was just a typo. I will propose this as an edit, but I just want you to be aware of it.
The fact that it is a graph and not a tree can be seen from those lines:
A 2 B 12 I 25
B 3 C 10 H 40 I 8
Here you have a circle already at A-B-I:
A
12/_\25
B 8 I
Having a circle by definition means it cannot be a tree!
There is one more thing one can see from the way I presented this subgraph:
the edges have weights, not the nodes.
Now let's take a look at your provided example:
A 2 B 12 I 25
B 3 C 10 H 40 I 8
C 2 D 18 G 55
D 1 E 44
E 2 F 60 G 38
F 0
G 1 H 35
H 1 I 35
First of all we can see that this adjacency list is either incorrect or already optimized for your needs. This can (for example) be seen from the lines
E 2 F 60 G 38
F 0
The first line here shows an edge from E to F, yet the second line says F had a degree of 0, but the degree is defined by the edges incident to it!
This is what the adjacency list would look like if it was 'complete':
A 2 B 12 I 25
B 4 A 12 C 10 H 40 I 8
C 3 B 10 D 18 G 55
D 2 C 18 E 44
E 3 D 44 F 60 G 38
F 1 E 60
G 3 C 55 E 38 H 35
H 3 B 40 G 35 I 35
We can see lots of redundancy because every edge occurs twice, this is why your 'optimized' adjacency list better suits your needs - would it be this 'complete' example one would do many useless checks.
However, you should only rely on this if you can be sure that all data given to your code is already 'optimized' (or rather in this format)! I will take this as a given from now on.
Let's talk about your data structure.
You may of course use your proposed array of strings, but to be honest, i would rather recommend something like #AmirAfghani's proposed data structure. Using his approach would make your work easier (as it - as he already pointed out - would be closer to your mental representation) and even more efficient (i guess, don't rely on this guess ;)) as you would be doing many operations on strings otherwise.
In the title you asked after Prim's algorithm, but in your actual question you said either Prim's or Kruskal's. I will go with Kruskal simply because his algorithm is way easier and you seem to accept both.
Kruskal's algorithm
Kruskal's algorithm is fairly simple, it's basically:
Start with every node, but no edges
Repeat the following as often as possible:
From all of the unused/unchosen edges choose the one with the fewest weight (if there are more than one: just pick one of them)
Check if this edge would cause a circle, if it does, mark it as chosen and 'discard' it.
If it doesn't cause a circle, use it and mark it as used/chosen.
That's all. It's really that simple.
However i would like to mention one thing at this point, i think it best fits here: there is no "the minimum spanning tree" in general, but "a minimum spanning tree" as there can be many, so your results may vary!
Back to your data structure! You may now see why it would be a bad idea to use an array of strings as a data structure. You would repeat many operations on strings (for example checking the weight of every edge) and strings are immutable, that means you cannot simply 'throw away' one of the edges or mark one of the edges in whatever way.
Using a different approach you could just set the weight to -1, or even remove the entry for the edge!
Depth-First Search
From what I have seen I think your main problem is deciding whether an edge would cause a circle or not, right?
To decide this, you will probably have to call a Depth-First Search algorithm and use its return value.
The basic idea is this: start from one of the nodes (i will call this node the root) and try to find a way to the node at the other end of the chosen edge (i will call this node the target node). (of course in the graph which doesn't have this edge yet)
Choose one unvisited edge incident to your root
Mark this chosen edge as visited (or something like that, whatever you like)
repeat the last two steps for the node on the other side of the visited edge
whenever there are no unvisited edges, go back one edge
if you are back at your root and have no unvisited edges incident to it remaining, you are done. return false.
if you at any point visit your target node, you are done. return true.
now, if this method returns true this edge would cause a circle.

Computational geometry: find where the triangle is after rotation, translation or reflection on a mirror

I have a small contest problem in which is given a set of points, in 2D, that form a triangle. This triangle may be subject to an arbitrary rotation, may be subject to an arbitrary translation (both in the 2D plane) and may be subject to a reflection on a mirror, but its dimensions were kept unchanged.
Then, they give me a set of points in the plane, and I have to find 3 points that form my triangle after one or more of those geometric operations.
Example:
5 15
8 5
20 10
6
5 17
5 20
20 5
10 5
15 20
15 10
Output:
5 17
10 5
15 20
I bet it's supposed to apply some known algorithm, but I don't know which. The most common are: convex hull, sweep plane, triangulation, etc.
Can someone give a tip? I don't need the code, only a push, please!
A triangle is uniquely defined (ignoring rotations, flips, and translations) by the lengths of its three sides. Label the vertices of your original triangle A,B,C. You're looking
for points D,E,F such that |AB| = |DE|, |AC| = |DF|, and |BC| = |EF|. The length is given by Pythagoras' formula (but you can save a square root operation at each test by comparing
the squares of the line segment lengths...)
The given triangle is defined by three lengths. You want to find three points in the list separated by exactly those lengths.
Square the given lengths to avoid bothering with sqrt.
Find the square of the distance between every pair of points in the list and only note those that coincide with the given lengths: O(V^2), but with a low coefficient because most lengths will not match.
Now you have a sparse graph with O(V) edges. Find every cycle of size 3 in O(V) time, and prune the matches. (Not sure of the best way, but here is one way with proper big-O.)
Total complexity: O(V^2) but finding the cycles in O(V) may be the limiting factor, depending on the number of points. Spatially sorting the list of points to avoid looking at all pairs should improve the asymptotic behavior, otherwise.
This is generally done with matrix math. This Wikipedia article covers the rotation, translation, and reflection matrices. Here's another site (with pictures).
Since the transformations are just rotation, scaling and mirroring, then you can find the points that form the transformed triangle by checking the dot product of two sides of the triangle:
For the original triangle A, B, C, calculate the dot product of AB.AC, BA.BC and CA.CB
For each set of three points D, E, F, calculate dot product of DE.DF and compare against the three dot products found in 1.
This works since AB.AC = |AB| x |AC| x cos(a), and two lengths and an angle between them defines a triangle.
EDIT: Yes, Jim is right, just one dot product isn't enough, you'll need to do all three, including ED.EF and FD.FE. So in the end, there's the same number of calculations in this as there is in the square distances method.

Help:Graph contest problem: maybe a modified Dijkstra or another alternative algorithm

I'm trying to do this contest exercise about graphs:
XPTO is an intrepid adventurer (a little too temerarious for his own good) who boasts about exploring every corner of the universe, no matter how inhospitable. In fact, he doesn't visit the planets where people can easily live in, he prefers those where only a madman would go with a very good reason (several millions of credits for instance). His latest exploit is trying to survive in Proxima III. The problem is that Proxima III suffers from storms of highly corrosive acids that destroy everything, including spacesuits that were especially designed to withstand corrosion.
Our intrepid explorer was caught in a rectangular area in the middle of one of these storms. Fortunately, he has an instrument that is capable of measuring the exact concentration of acid on each sector and how much damage it does to his spacesuit. Now, he only needs to find out if he can escape the storm.
Problem
The problem consists of finding an escape route that will allow XPTO to escape the noxious storm. You are given the initial energy of the spacesuit, the size of the rectangular area and the damage that the spacesuit will suffer while standing in each sector.
Your task is to find the exit sector, the number of steps necessary to reach it and the amount of energy his suit will have when he leaves the rectangular area. The escape route chosen should be the safest one (i.e., the one where his spacesuit will be the least damaged). Notice that XPTO will perish if the energy of his suit reaches zero.
In case there are more than one possible solutions, choose the one that uses the least number of steps. If there are at least two sectors with the same number of steps (X1, Y1) and (X2, Y2) then choose the first if X1 < X2 or if X1 = X2 and Y1 < Y2.
Constraints
0 < E ≤ 30000 the suit's starting energy
0 ≤ W ≤ 500 the rectangle's width
0 ≤ H ≤ 500 rectangle's height
0 < X < W the starting X position
0 < Y < H the starting Y position
0 ≤ D ≤ 10000 the damage sustained in each sector
Input
The first number given is the number of test cases. Each case will consist of a line with the integers E, X and Y. The following line will have the integers W and H. The following lines will hold the matrix containing the damage D the spacesuit will suffer whilst in the corresponding sector. Notice that, as is often the case for computer geeks, (1,1) corresponds to the upper left corner.
Output
If there is a solution, the output will be the remaining energy, the exit sector's X and Y coordinates and the number of steps of the route that will lead Rodericus to safety. In case there is no solution, the phrase Goodbye cruel world! will be written.
Sample Input
3
40 3 3
7 8
12 11 12 11 3 12 12
12 11 11 12 2 1 13
11 11 12 2 13 2 14
10 11 13 3 2 1 12
10 11 13 13 11 12 13
12 12 11 13 11 13 12
13 12 12 11 11 11 11
13 13 10 10 13 11 12
8 3 4
7 6
4 3 3 2 2 3 2
2 5 2 2 2 3 3
2 1 2 2 3 2 2
4 3 3 2 2 4 1
3 1 4 3 2 3 1
2 2 3 3 0 3 4
10 3 4
7 6
3 3 1 2 2 1 0
2 2 2 4 2 2 5
2 2 1 3 0 2 2
2 2 1 3 3 4 2
3 4 4 3 1 1 3
1 2 2 4 2 2 1
Sample Output
12 5 1 8
Goodbye cruel world!
5 1 4 2
Basically, I think we have to do a modified Dijkstra, in which the distance between nodes is the suit's energy (and we have to subtract it instead of suming up like is normal with distances) and the steps are the ....steps made along the path. The pos with the bester binomial (Energy,num_Steps) is our "way out".
Important : XPTO obviously can't move in diagonals, so we have to cut out this cases.
I have many ideas, but I have such a problem implementing them...
Could someone please help me thinking about this with some code or, at least, ideas?
Am I totally wrong?
Since this is a contest problem, I'll just give a small hint:
In this example, it's the nodes that have weight, not the edges. One way of converting such a graph to the usual kind is to replace each node with two nodes, an in node and an out node, and a directed edge from in to out with weight equal to the original node's weight. Then for each directed edge in the original graph, put a directed edge from the out node of one to the in node of the next.
Your idea sounds good - go with it.
By the way, when working these problems, try to work out the implementation for yourself. It rarely helps to simply see someone else's implementation. Ask for help on the algorithm if you need to, but implement it yourself.
You don't have to treat this with any unconventional conversions like you said (subtracting instead of adding, etc).
The shortest path from one node to another is one that minimizes the total damage to the suit along the way, regardless of whether or not this journey will kill you.
Just find the shortest path from START to EXIT, summing up edge weights as is usual Dijkstra approach, and then consider if this shortest path is feasible for the given suit power. If it isn't, then Goodbye cruel world!.
If you insist on pruning the search once you know that you can definitely not reach the EXIT, then adding it after the above implementation is trivial: as you're expanding your search horizon in your Dijkstra search, if even going to the next closest node to expand from kills you, then the rest of search space also will, so you can just abort and Goodbye cruel world!.
As for the graph itself, conceptually this is what you want. The vertices of the directed graph consists of all nodes in the grid, plus an artificial EXIT node.
All edge nodes have a directed edge to EXIT; the weight of these edges is 0
All neighboring (non-diagonal) node have directed edges between them
From node n1 to n2, the weight of the edge (i.e. the cost damage of travelling from n1 to n2) is the damage incurred by staying at node n2 (let's call this damageAt[n2], which you get from D matrix in input).
So minimum total amount of damage that one must sustain to go from START to EXIT is damageAt[START] + costOf(shortestPathBetween(START, EXIT)).
In summary, this approach:
Only requires standard Dijkstra implementation
Requires only very small modification to add pruning
Requires only very simple transformation from the input grid to the directed graph

Categories