Tree Traversal, the output is wrong - java

I am trying to solve this problem: https://leetcode.com/problems/house-robber-iii/
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Now with this input:
Input: [4,1,null,2,null,3]
That should be this tree:
Now in my opinion the correct output is 4+2 = 6 but leetcode says the correct is 7.
Did I draw wrong the tree? How can you obtain a max 7 rob given that tree?

Number 4 and 3 are also not connected, so 4+3 would also count and would be higher than 4 + 2. It is about nodes that are connected. As long as they are not directly connected, the thief can rob them, thus 4+3 could be robbed.

What's stopping you from robbing 4 + 3 = 7? Those two "houses" are not directly linked.

Related

Java - quidditch program using arraylists

I am supposed to create a quidditch program using arraylists but I am kinda confused and my teacher isn't helpful whatsoever. I know how to create the array list and add them, remove, the basic uses of array list. The way he has the directions worded confuse me, any help about where to start would be great.
I can do most of the work for this program,
the main confusion for me is part a, how to pair the teams to go against each other and how to do the multiple rounds.
Im not asking for anyone to do this program, I'm just asking for some help, explanation and pointers on where to start. Thanks a lot guys.
Directions:
Create an ArrayList of Strings containing the names of your 8 ‘teams’. Use humorous names for your teams (Dwarves, Wizards, Dinosaurs, etc.)
Code a method public void playGame(int teamA, int teamB, ArryList teams)
a. teamA and teamB are the indices (sic. Indexes) of the teams that are playing the current game. You will use these to retrieve the String name of the team.
For our purposes a Quiddich game has four quarters:
b. Each team randomly scores 0 to 4 goals worth 10 points each per quarter (0 – 40 points per quarter.
c. Each quarter, there is a 15% chance that a team will capture the Golden snitch. If that happens the game ends immediately and that team wins.
(First determine if a team got the snitch, then if one did randomize which one wins with even probability.)
d. The method should display the results for each quarter that is played and indicate the final score or if the teams won by capturing the snitch.
e. There are no ties. Play additional sudden death quarters until one team wins.
f. Your method should remove the loosing team from the ArrayList and print a msg that that team (using the String name) has been eliminated from the Tourney.
 
Code your main program to display the list of teams. Then run the tournament. For each round pit every other team against one another.
a. First round: 4 games reduces teams to 4 remaining.
b. Second round: 2 games reduces teams to final 2
c. Final round: 1 game determines the tournament winner.
Each time show the list of remaining teams and use your method to run the games for that round. (Hint: just use even/odd indices for the pairings: Team index 0 plays team index 1, team index 2 plays team index 3, etc.)
I think the answer is in the last point - the teams shouldn't play in a "league" way (one vs all others) but in a "cup" way (the one that loses won't play anymore). The teams should be divided like this: even vs odd. I believe the simplest way to do this would be:
for(int i = 0; i < teams.size(); i = i + 2) {
playGame(i, i + 1, teams);
}
Assuming, that there will be even number of all teams of course.

Find the hidden nodes between two nodes - graph - java

My English is not very well, BUT I will try my best to explain my issue here.
I am working on an application in which I have to create graph. For now I am using GraphStream.
Requirements for my graph is very complicated, which is :
I have a table named CDR(Call Data Record) in which I have 2 columns ANUMBER and BNUMBER. The structure of table is very clear that it shows that Anumber called Bnumber and there is another column for DATETIME, which shows the date and time of call. BUT I need here only two columns.
Lets say we have 4 numbers here : 123, 456 ,789 ,000 and table structure is like this
Anumber Bnumber
------- -------
123 456
123 789
456 789
789 000
456 000
My table here clearly shows that 123 didn't call 000 But 123 called 456 and 789 and these two numbers called 000 So I have to show the directed graph between 123 and 000 which probably shows like this 123->456->000 and 132->789->000
So the issue is I don't know how to find this path between 123 and 000. There may be more than 2 numbers like 5 or 6 numbers and I have to find the hidden numbers between all the given 5 or 6 numbers AS in the above scenario 456 and 789 are hidden numbers between 132 and 000.
And one thing more my table contains more than 20 million rows and in future obviously the number of rows will grow very fast as user calls each other.
WHAT I HAVE DONE SO FAR:
I have done some R&D on this issue but couldn't found any good library or any solution for this. So far, I think Dijkstra's Algorithm is best for my scenario as GraphStream luckily provides this algorithm here.
What I want from you guys, Give me an idea that Will this algorithm will give me required result OR I have to find any other algo or graph library which will suits best for my problem. I am not good at ALGO's thats why I am here for any help or guideline If you guys can gave me.
Thanks
You don't need Dijkstra's algorithm at all, since you don't have costs on edges. You need simple BFS algorithm.
Here is simple implementation but you should add 'labels' array to mark visited nodes. So after BFS you can restore pass from each node to source node(123 in your case) or say that node cannot be reached from given node(if label for this node remains 0).
You should add label in the following way:
all labels equals 0 on start
when you visit new node you set it's label as current_node_label+1
But Dijkstra's can help you if you set cost of each edge as 1. It's just not efficient way to sole you problem.

Testing multible combinations

First of all I want to say, that I looked online for a possible or similar solution but did not find anything, might have been looking for the wrong keywords but please excuse my rather simple question.
However, currently I am trying to implement a java function that - on an input of an integer (e.g. 10) gives me every possible solutions on how to divide this by 2 or 1.
And I literally have no clue on how to even start, as there is no pattern to it or anything that I have done is relatable.
However this is an old exam from my professor, so there is a good and short solution I am just not seeing.
Thank you very much for your help and time :)
edit:
The method I am trying to imlement would look as follows:
static void possibilities (int i){ }
I would be able to give an integer (3 for example) and then as output (through Sys.out) all possibilities of all possible combinations of 1 and 2's, for example for 3:
(1,1,1)
(2,1)
(1,2)
Or for 2:
(1,1)
(2)
Here is what I think would work:
say the input is 5 so the very 1st combination will be: (1,1,1,1,1) right? now we add the first two number so it is (2,1,1,1) and store it in a string i.e. "2111" now we find all the permutations of this string (code 4 this is available), now we add the next 1,1 pair so it will look like (2,2,1) i.e "221" and again same process of permutations.
We keep repeating this till the string has just one '1' present or no '1' present, try checking for the number 4, same thing.

The Fastest Way Algorithm

I need to figure out how to solve this problem. I am using Java but it doesn't matter for now. I don't need any codes since I have to do that myself I just need some advices about the algorithm since I can't find any fast ways to do this.(My solution took too long when compiling)
Question is:
There are 4 cities. Each has different routes from one to other(16 routes totally)
Going from City 1 to City 4 is different than going to City 1 from City 4(all routes are one-way) that's why they have different values.
I have the list of required times for each road which is totally 16. Actually the list will be typed by the user when the program initiates but you can assume that I have the list for now.
After we got the required times the user chooses a starting and an ending city and the program has to find the minimum duration for that travel.
Example:
0 18 15 8
18 0 7 3
7 16 0 19
10 14 19 0
This is a table of travel durations. i(row) x j(column) and the values show the travel duration from i to j city.
When the user inputs "4 2" which means from city 4 to city 2, the the output as answer should be 14
But when the user inputs "2 1" the the output as answer should be 13(3+10). First from city 2 to city 4 which is 3 hours and than from city 4 to city 1 which is 10 hours and totally it makes 13 hours.
So the chosen route doesn't need to be the direct route any number of routes can be used between two cities but with the most fastest way.
This 4x4 table was just an example for 4 cities. (Which is all I have also). The algorithm should work for max 100 cities. The user will type the number of cities before filling the table for travel durations between each of them.
I may find a solution for 4 cities but It doesn't work for 100 cities. I also tried permutation method with java but as I said it took too long to compile. However compiling proccess musn't take longer than 4 seconds.
Sorry for the long and boring question of mine but I hope someone can make a useful suggestion.
I have figured out how to do it, so answering this myself. I have managed to make it work by editing the code I have found here. It works really fast and flawless.

Presidential Seating Backtracking

I have a problem in front of me that I can't grasp, even though I grasp the concept of backtracking well. I have been unable to find any information on this specific problem, and I am unaware if it goes by another name. The problem is to construct a backtracking algorithm that will print out the list of combinations of seating that N number of "presidents" can sit at a round table without sitting next to the same person twice. For example, you give it an input 8, it gives you the output,
1 2 3 4 5 6 7 8
1 3 5 2 6 8 4 7
1 4 2 7 5 8 3 6
Now I have constructed my own backtracking algorithms for simple games (checkers, n-queens, tic-tac-toe), however these that I have worked with have started with a blank canvas and didn't require this type of implementation. What I am asking for is a bit of guidance and insight, or links to more information to this problem as all that was given was about a page and a half, mostly talking about how the combination 1 2 3 4 is effectively the same as 1 4 3 2 in this particular problem. This needs to be done using a backtracking method and that's what is making me confused. If we were give free rein to find solutions I could easily do it. Any help is appreciated.
Thanks!
I'm thinking you'll have to add information about who sat next to who already to the backtracking algorithm state:
You start with, say 1. You seat 2 next to him, and record this "pairing" in the current partial solution. (Literally just an unordered pair of president IDs. An easy way of implementing an unordered pair of numbers is to have the constructor of that class store the smaller ID in the first element of the pair, and the greater ID in the second element.) So you have a partial solution 1 2 …, with the pairing 1-2.
When you reach to a complete solution, you add all its pairings to a "global" list of pairings. This will be used in future searches. I.e. if you get the solution 1 2 3 4 5 6 7 8, you save the pairings 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 1-8.
Now, when doing a search, you have a partial solution x y z … – the last president seated so far is z, and the pairings in this partial solution are x-y and y-z. To seat the next president, you need to look at every president that's:
Not seated so far. (And thus not included in the partial solution's pairings.)
Not paired with z in the global pairings.
If no such president is available, you discard the partial solution and backtrack.
That said, I'm working off the top of my head here, so you'd be well advised to actually doublecheck if I missed any edge cases by using a straightforward brute force implementation and comparing the results.
A very rough pseudocode will look like this:
global flag // I know it is a bad practice but can't think of a better idea at this point
back (PresidentList, chairNumber, computedList)
if (PresidentList.size() == 0)
if (computedList doesn't violate any global distribution)
add computedList to globalList
add distirbution of computedList to global distirbution
set flag;
else return;
else if (flag is set and chairNumber > 2) return;
else if (flag is set and chairNumber = 2) un set flag; return;
else if (chairNumber == maxChairs-1)
// at this point there should be only one president in PresidentList
if (PresidentList.back() can sit with computedList.back() and computedList.front())
remove president from PreseidentList, add president to computedList
back(PresidenList, chairNumber+1,computedList)
else return;
else
for every president in PresidentList
if (president can sit with computedList.back())
remove president from PreseidentList, add president to computedList
back(PresidentList,chairNumber+1,computedList);
You always check if a president can sit near some other president only according to the global distribution variable.
In the main function just run a loop for PresidentList that will start back with that president being as the first one.
The idea of the flag is as follows: when you add a distribution and a list to the global list, back runs already a lot of branches which have the same prefix as the list you just added and hence are already bad. To close all those lists you force the back to stop branching and return to the point when it can set a new 2nd element in the list to compute i.e. get back to the loop if the last else branch of the function.

Categories

Resources