As you will see in the below output, nodes with values 10 and 15 are not being added.
The whole code is below
..............
.............
...............
..............
.............
#include<iostream>
using namespace std;
#define SPACE 10
class TreeNode{
public:
int value;
TreeNode *left;
TreeNode *right;
TreeNode(){
value = 0;
left = NULL;
right = NULL;
}
TreeNode(int v){
value = v;
left = NULL;
right = NULL;
}
};
class BST{
public:
TreeNode *root;
BST(){
root = NULL;
}
bool isEmpty(){
if(root == NULL)
return true;
else
return false;
};
void insertNode(TreeNode *new_node){
if(root == NULL){
root = new_node;
cout<<"Node entered at root"<<endl;
}
else{
TreeNode *temp = root;
while(temp!=NULL){
if(new_node->value == temp->value){
cout<<"Node already exist"<<endl;
break;
}
else if((new_node->value < temp->value) && (temp ->left == NULL)){
temp->left = new_node;
cout<<"Inserted at right"<<endl;
break;
}
else if (new_node->value < temp->value){
temp = temp->left;
break;
}
else if((new_node->value > temp->value) && (temp ->right == NULL)){
temp->right = new_node;
cout<<"Inserted at left"<<endl;
break;
}
else if (new_node->value > temp->value){
temp = temp->right;
break;
}
}
}
}
void print2D(TreeNode * r, int space) {
if (r == NULL) // Base case 1
return;
space += SPACE; // Increase distance between levels 2
print2D(r -> right, space); // Process right child first 3
cout << endl;
for (int i = SPACE; i < space; i++) // 5
cout << " "; // 5.1
cout << r -> value << "\n"; // 6
print2D(r -> left, space); // Process left child 7
}
};
int main(){
BST obj;
int option, val;
do {
cout << "What operation do you want to perform? " <<
" Select Option number. Enter 0 to exit." << endl;
cout << "1. Insert Node" << endl;
//cout << "2. Search Node" << endl;
//cout << "3. Delete Node" << endl;
cout << "2. Print/Traversal BST values" << endl;
//cout << "5. Height of Tree" << endl;
//cout << "6. Clear Screen" << endl;
cout << "0. Exit Program" << endl;
cin >> option;
//Node n1;
TreeNode *newNode = new TreeNode();
switch (option){
case 0:
break;
case 1:
cout<<"Insert Node"<<endl;
cout<<"Enter the value of the node"<<endl;
cin>>val;
newNode->value = val;
obj.insertNode(newNode);
break;
case 2:
cout<<"Print value"<<endl;
obj.print2D(obj.root, 5);
break;
default:
cout<<"Enter appropriate option"<<endl;
} //switch
}while(option!=0);
}
OUTPUT:
What operation do you want to perform? Select Option number. Enter 0 to exit.
1. Insert Node
2. Print/Traversal BST values
0. Exit Program
1
Insert Node
Enter the value of the node
30
Node entered at root
What operation do you want to perform? Select Option number. Enter 0 to exit.
1. Insert Node
2. Print/Traversal BST values
0. Exit Program
1
Insert Node
Enter the value of the node
18
Inserted at right
What operation do you want to perform? Select Option number. Enter 0 to exit.
1. Insert Node
2. Print/Traversal BST values
0. Exit Program
1
Insert Node
Enter the value of the node
45
Inserted at left
What operation do you want to perform? Select Option number. Enter 0 to exit.
1. Insert Node
2. Print/Traversal BST values
0. Exit Program
1
Insert Node
Enter the value of the node
10
What operation do you want to perform? Select Option number. Enter 0 to exit.
1. Insert Node
2. Print/Traversal BST values
0. Exit Program
1
Insert Node
Enter the value of the node
15
What operation do you want to perform? Select Option number. Enter 0 to exit.
1. Insert Node
2. Print/Traversal BST values
0. Exit Program
2
Print value
45
30
18
As you see the node 10 and 15 is not being added to the tree. I've tried every single way.
Plz if anyone has solution do provide it. Thank you
Make temp=temp->left in first else if block and remove second else if block and do same for 3rd and 4 th else if block
I took reference of code from GeeksForGeeks for merging of two sorted linked lists.
#include <bits/stdc++.h>
using namespace std;
/* Link list node */
struct Node
{
int data;
struct Node* next;
};
void MoveNode(Node **destRef, Node **sourceRef){
cout << "pp: " << (*sourceRef) << endl;
Node *tempNode = *sourceRef;
cout << "tt:" << tempNode->next << endl;
*sourceRef = tempNode->next;
tempNode->next = *destRef;
*destRef = tempNode;
cout << "qq: " << (*sourceRef) << endl;
}
struct Node* SortedMerge(Node *a, Node *b){
Node *dummy;
Node *tail;
dummy->next = NULL;
tail = dummy;
cout << "hii" << endl;
while(true){
if(a==NULL){
cout << "aa" << endl;
tail->next = b;
break;
}
else if(b==NULL){
cout << "bb" << endl;
tail->next = a;
break;
}
if(a->data < b->data){
cout << "cc" << endl;
MoveNode(&(tail->next), &a);
tail = tail->next;
}
else if(a->data >= b->data){
cout << "dd" << endl;
// cout << "b->data: " << b << endl;
MoveNode(&(tail->next), &b);
// b = b->next;
// cout << "b->data: " << b << endl;
// cout << "b->data: " << b->data << endl;
tail = tail->next;
}
}
return dummy->next;
}
/* Function to insert a node at the beginning of the
linked list */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while (node!=NULL)
{
printf("%d ", node->data);
node = node->next;
}
cout << endl;
}
/* Drier program to test above functions*/
int main()
{
/* Start with the empty list */
struct Node* res = NULL;
struct Node* a = NULL;
struct Node* b = NULL;
/* Let us create two sorted linked lists to test
the functions
Created lists, a: 5->10->15, b: 2->3->20 */
push(&a, 15);
push(&a, 10);
push(&a, 5);
push(&b, 20);
push(&b, 3);
push(&b, 2);
/* Remove duplicates from linked list */
res = SortedMerge(a, b);
printf("Merged Linked List is: \n");
printList(res);
return 0;
}
For the given example in the main function, the program gives wrong output if I do not print the node values in the second else if of while loop in SortedMerge function. And if I do print them the program gives correct output. I find it very strange. Can someone please help me out?
I am trying to solve this problem, I think I have come up with a correct answer, but I am keep getting WA (wrong answer) response from the judge.
http://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1452
The problem distilled, is, given a 1 - * relationship between party and person, 1 - * relationship between person and club. Find a 1 - 1 relationship between person and club such that for all person related to a club, the number of persons belong to a any party is less than half of the number of club.
For example, let say we have
Person1 belongs to Party1 and Club1, Club2
Person2 belongs to Party2 and Club2, Club3
Person3 Belongs to Party3 and Club3, Club1
There are two assignments possible.
Person1 Club1
Person2 Club2
Person3 Club3
and
Person1 Club2
Person2 Club3
Person3 Club1
My idea is to model this problem as a maximum flow problem as follow:
For simplicity, let say there are two parties, four persons, and three clubs.
0 is the master source
1, 2 are the nodes representing the two parties
3, 4, 5, 6 are the nodes representing the four persons
7, 8, 9 are the nodes representing the three clubs.
10 is the master sink
master source connects to each party with capacity = (3 + 1)/2 - 1 = 1. That represents there can only be at most 1 person of 1 party representing in the council (or otherwise 2 will be equals to or more than half)
for each party person pair, have a link of capacity 1. That represents each person have only 1 party and used one seat in the previously allocated number.
for each person club pair, have a link of capacity 1. That represents each person can represent one club only.
Last but not least, all clubs goes to sink with capacity 1.
If the graph above has a maximum flow equals to the number of clubs - then there exist an assignment.
I can prove the design is correct as follow:
=>
If there exist a maximum flow of the size, each club node must be sending flow of value 1, implies each club node has exactly one person representing it. The representation respect the constraint of party participation as it has at most that many person in a party representing by the party node flow.
<=
If there is a representation, construct the flow as above, so that a flow exist. The flow is maximum because the maximal possible flow is constrainted by edge connecting to the sink.
So something must be wrong either with the arguments above, or with the implementation.
Without further ado, this is my source code:
#include "stdafx.h"
// http://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=1452
// #define LOG
#include "UVa10511.h"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <map>
#include <queue>
using namespace std;
int UVa10511_assign_person_number(map<string, int>& person_numbers, map<int, string>& person_namings, string person_name);
int UVa10511_assign_party_number(map<string, int>& party_numbers, map<int, string>& party_namings, string party_name);
int UVa10511_assign_club_number(map<string, int>& club_numbers, map<int, string>& club_namings, string club_name);
int UVa10511_Edmonds_Karps(vector<vector<int>>& capacities, vector<vector<int>>& adjacency_list, int src, int dst);
int UVa10511()
{
string line;
int number_of_test_cases;
cin >> number_of_test_cases;
getline(cin, line); // consume the blank link after the number of test cases
getline(cin, line); // consume the blank link before the first test case
for (int test_case = 0; test_case < number_of_test_cases; test_case++)
{
map<string, int> person_numbers;
map<int, string> person_namings;
map<string, int> party_numbers;
map<int, string> party_namings;
map<string, int> club_numbers;
map<int, string> club_namings;
vector<pair<int, int>> party_members;
vector<pair<int, int>> person_clubs;
while(getline(cin, line) && line != "" && line != " ")
{
string person_name;
string party_name;
string club_name;
stringstream sin(line);
sin >> person_name >> party_name;
int person_id = UVa10511_assign_person_number(person_numbers, person_namings, person_name);
int party_id = UVa10511_assign_party_number(party_numbers, party_namings, party_name);
party_members.push_back(pair<int, int>(party_id, person_id));
while(sin >> club_name)
{
int club_id = UVa10511_assign_club_number(club_numbers, club_namings, club_name);
person_clubs.push_back(pair<int, int>(person_id, club_id));
}
}
int number_of_parties = party_numbers.size();
int number_of_persons = person_numbers.size();
int number_of_clubs = club_numbers.size();
int number_of_nodes =
/* master source */ 1 +
/* parties */ number_of_parties +
/* person */ number_of_persons +
/* clubs */ number_of_clubs +
/* master sink */ 1;
vector<vector<int>> capacities;
vector<vector<int>> adjacency_list;
capacities.resize(number_of_nodes);
adjacency_list.resize(number_of_nodes);
for (int src = 0; src < number_of_nodes; src++)
{
capacities[src].resize(number_of_nodes);
for (int dst = 0; dst < number_of_nodes; dst++)
{
capacities[src][dst] = 0;
}
}
int max_party_participants = (number_of_clubs - 1) / 2; // Floor intended, not equal or more than half
for (int p = 0; p < number_of_parties; p++)
{
int party_node = p + 1;
capacities[0][party_node] = max_party_participants;
adjacency_list[0].push_back(party_node);
adjacency_list[party_node].push_back(0);
}
int person_node_start = 1 + number_of_parties;
for (vector<pair<int, int>>::iterator pmi = party_members.begin(); pmi != party_members.end(); pmi++)
{
int party_id = pmi->first;
int person_id = pmi->second;
int party_node = party_id + 1;
int person_node = person_node_start + person_id;
capacities[party_node][person_node] = 1;
adjacency_list[party_node].push_back(person_node);
adjacency_list[person_node].push_back(party_node);
}
int club_node_start = 1 + number_of_parties + number_of_persons;
for (vector<pair<int, int>>::iterator pci = person_clubs.begin(); pci != person_clubs.end(); pci++)
{
int person_id = pci->first;
int club_id = pci->second;
int person_node = person_node_start + person_id;
int club_node = club_node_start + club_id;
capacities[person_node][club_node] = 1;
adjacency_list[person_node].push_back(club_node);
adjacency_list[club_node].push_back(person_node);
}
for (int c = 0; c < number_of_clubs; c++)
{
int club_node = club_node_start + c;
capacities[club_node][number_of_nodes - 1] = 1;
adjacency_list[club_node].push_back(number_of_nodes - 1);
adjacency_list[number_of_nodes - 1].push_back(club_node);
}
#ifdef LOG
cout << "digraph {" << endl;
for (int src = 0; src < number_of_nodes; src++)
{
for (vector<int>::iterator di = adjacency_list[src].begin(); di != adjacency_list[src].end(); di++)
{
int dst = *di;
cout << src << "->" << dst << " [label=\"" << capacities[src][dst] << "\"];" << endl;
}
}
cout << "}" << endl;
#endif
int total_flow = UVa10511_Edmonds_Karps(capacities, adjacency_list, 0, number_of_nodes - 1);
if (test_case > 0)
{
cout << endl;
}
if (total_flow == number_of_clubs)
{
for (vector<pair<int, int>>::iterator pci = person_clubs.begin(); pci != person_clubs.end(); pci++)
{
int person_id = pci->first;
int club_id = pci->second;
int person_node = person_node_start + person_id;
int club_node = club_node_start + club_id;
if (capacities[person_node][club_node] == 0)
{
cout << person_namings[person_id] << " " << club_namings[club_id] << endl;
}
}
}
else
{
cout << "Impossible." << endl;
}
}
return 0;
}
int UVa10511_assign_party_number(map<string, int>& party_numbers, map<int, string>& party_namings, string party_name)
{
int party_number;
map<string, int>::iterator probe = party_numbers.find(party_name);
if (probe == party_numbers.end())
{
party_number = party_numbers.size();
party_numbers.insert(pair<string, int>(party_name, party_number));
party_namings.insert(pair<int, string>(party_number, party_name));
}
else
{
party_number = probe->second;
}
return party_number;
}
int UVa10511_assign_person_number(map<string, int>& person_numbers, map<int, string>& person_namings, string person_name)
{
int person_number;
map<string, int>::iterator probe = person_numbers.find(person_name);
if (probe == person_numbers.end())
{
person_number = person_numbers.size();
person_numbers.insert(pair<string, int>(person_name, person_number));
person_namings.insert(pair<int, string>(person_number, person_name));
}
else
{
person_number = probe->second;
}
return person_number;
}
int UVa10511_assign_club_number(map<string, int>& club_numbers, map<int, string>& club_namings, string club_name)
{
int club_number;
map<string, int>::iterator probe = club_numbers.find(club_name);
if (probe == club_numbers.end())
{
club_number = club_numbers.size();
club_numbers.insert(pair<string, int>(club_name, club_number));
club_namings.insert(pair<int, string>(club_number, club_name));
}
else
{
club_number = probe->second;
}
return club_number;
}
int UVa10511_Edmonds_Karps(vector<vector<int>>& capacities, vector<vector<int>>& adjacency_list, int src, int dst)
{
int total_flow = 0;
// Step 2: Edmonds Karp's
vector<int> parents; // Allow back-tracking the path found from bfs
int number_of_nodes = capacities.size();
parents.resize(number_of_nodes); // avoid reallocation
while (true)
{
// Step 2.1: Use BFS to find an augmenting flow
queue<int> bfs_queue;
for (int n = 0; n < number_of_nodes; n++)
{
parents[n] = -1; // indicating the node is not enqueued
}
parents[src] = -2; // indicating the node is enqueued but no actual parent because this is the root
bfs_queue.push(src);
while (bfs_queue.size() > 0)
{
int current = bfs_queue.front();
bfs_queue.pop();
for (vector<int>::iterator ni = adjacency_list[current].begin(); ni != adjacency_list[current].end(); ni++)
{
int neighbor = *ni;
if (parents[neighbor] == -1 && capacities[current][neighbor] > 0)
{
parents[neighbor] = current;
bfs_queue.push(neighbor);
if (neighbor == dst)
{
break;
}
}
}
if (parents[dst] != -1)
{
break;
}
}
if (parents[dst] == -1)
{
break;
}
else
{
// We have found an augmenting path, go through the path and find the max flow through this path
int cur = dst;
bool first = true;
int max_flow_through_path = 0;
while (true)
{
int src = parents[cur];
if (src != -2)
{
int dst = cur;
int available = capacities[src][dst];
#ifdef LOG
cout << src << "--" << available << "->" << dst << endl;
#endif
cur = parents[cur];
if (first)
{
max_flow_through_path = available;
first = false;
}
else
{
max_flow_through_path = min(max_flow_through_path, available);
}
}
else
{
break;
}
}
#ifdef LOG
cout << "flowing " << max_flow_through_path << endl << endl;
#endif
total_flow += max_flow_through_path;
// Flow the max flow through the augmenting path
cur = dst;
while (true)
{
int src = parents[cur];
if (src != -2)
{
capacities[src][cur] -= max_flow_through_path;
capacities[cur][src] += max_flow_through_path;
cur = parents[cur];
}
else
{
break;
}
}
}
}
return total_flow;
}
The source code is also posted in
https://github.com/cshung/Competition/blob/master/Competition/UVa10511.cpp
The same Edmonds Karps procedure is used to pass some other UVa problems, so I think it should be fine.
UVa820, UVa10480, UVa10779, UVa11506, UVa563 are all accepted with this Edmonds Karp procedure
(These code can be found in the Git repository as well)
I have even debugging the case where Edmond Karps make a wrong choice to being with a fixed it with an augmenting path for this test case
1
Person1 Party1 Club1 Club2
Person2 Party2 Club3
Person3 Party3 Club1
As my Edmond Karps used BFS in the adjacency list order, The chosen paths are
Master Source -> Party1 -> Person1 -> Club1 -> Master Sink
Master Source -> Party2 -> Person2 -> Club3 -> Master Sink
Master Source -> Party3 -> Person3 -> Club1 -> Person1 -> Club2 -> Master Sink [This used the reverse edge and proved going through reverse edge works]
Now I am really stuck, really don't know what's wrong, any help is appreciated.
Your thinking for this problem is correct, it is a typical problem that use maximum flow algorithm.
I have read your code over and over again, I can't find any mistake. Then I change the way you handle the input, then I got accept from UVA.
Just change the code
// you code
cin >> number_of_test_cases;
getline(cin, line); // consume the blank link before the first test case
getline(cin, line); // consume the blank link before the first test case
//line 43
while(getline(cin, line) && line != "" && line != " ")
// change to
scanf("%d\n", &number_of_test_cases);
//line 43
// while(getline(cin, line) && line.length() > 0)
After change the code, I got accept from uva .
Hope get accept response from you.
I'm working on a red black tree assignment for my class and I'm having some trouble with the insertion function. My problem is that my root node value is being changed somehow between the end of the insert function and the beginning of insert being called again. I ran it through the debugger in Visual Studio and saw no reason why the root key should be altered like it is. I'm sure there are many other errors in my code thus far because I decided to focus on this before the rest of the program. Once this is fixed I will go back and correct other errors. I have not yet implemented the fix-up function for correcting the tree after insertion so don't worry about red-black tree properties being met. If you have any questions or if I haven't given enough info then please let me know.
/ rbtree.cpp
#include <iostream>
#include <iomanip>
#include "rbtree.h"
using std::cout;
using std::setw;
using std::endl;
void RBTree::reverseInOrderPrint(Node *x, int depth) {
if ( x != nil ) {
reverseInOrderPrint(x->right, depth+1);
cout << setw(depth*4+4) << x->color << " ";
cout << *(x->key) << " " << *(x->value) << endl;
reverseInOrderPrint(x->left, depth+1);
}
}
RBTree::RBTree()
{
nil = new Node();
root = nil;
}
RBTree::~RBTree()
{
//delete[] root;
}
void RBTree::rbInsert(const string& key_given, const string& value_given)
{
//if(root != nil)
//cout << *(root -> key) << " <- root key at beginning of insert function" << endl;
Node* input_node = new Node(key_given, value_given, nil);
Node* target = root;
Node* target_parent = nil;
while(target != nil)
{
target_parent = target;
if(input_node -> key -> compare(*(target -> key)) < 0)
target = target -> left;
else
target = target -> right;
}
input_node -> parent = target_parent;
if(target_parent == nil)
root = input_node;
else if(input_node -> key -> compare(*(target_parent -> key)) < 0)
target_parent -> left = input_node;
else
target_parent -> right = input_node;
input_node -> left = nil;
input_node -> right = nil;
input_node -> color = 'R';
/*rbInsertFixup(input_node);
cout << *(root -> key) << " <- root key at end of insert function" << endl;
if(root -> left != nil)
cout << *(root -> left -> key) << " is root's left child" << endl;
if(root -> right != nil)
cout << *(root -> right -> key) << " is root's right child" << endl;*/
}
//void RBTree::rbInsertFixup(
RBTree::Node::Node()
{
parent = NULL;
left = NULL;
right = NULL;
color = 'B';
key = NULL;
value = NULL;
}
RBTree::Node::Node(const string& key_given, const string& value_given, Node* nil_pntr)
{
parent = nil_pntr;
left = nil_pntr;
right = nil_pntr;
color = 'R';
key = &key_given;
value = &value_given;
}
RBTree::Node::~Node()
{
if(left != NULL)
delete left;
if(right != NULL)
delete right;
}
int main()
{
RBTree tree;
tree.rbInsert("Zack", "His Birthday");
tree.rbInsert("Terri", "Her Birthdays");
tree.rbInsert("Zzck", "HBD");
return 0;
}
Here is an example of the output I get when running this code:
Zack <- root key at end of insert function
Terri <- root key at beginning of insert function
Terri <- root key at end of insert function
Terri is root's right child
Zzck <- root key at beginning of insert function
Zzck <- root key at end of insert function
Zzck is root's right child
you need to compare 2 strings, you have to dereference the input_node->key and because you are using compare to check the two strings try using "<" or ">" and i am pretty sure it will work have something like this * (input_node -> key) <*(target_parent -> key)
I have a problem trying to insert elements on my BST given an unsorted array. The output gives me a segmentation fault, but I can't pinpoint the location of my error. I'm pretty sure that something is wrong with my insert, but I'm not sure what. If anyone can give me insight that would be much appreciated.
#include <iostream>
using namespace std;
struct BST{
BST* left;
BST* right;
int data;
};
BST* init(int data){
BST* a = new BST;
a->data = data;
a->right = NULL;
a->left = NULL;
return a;
}
BST* insert(BST* root, int data){
if (root == NULL)
root = new BST;
else{
BST* current = root;
if (current->data >= data)
insert(current->right, data);
else
insert(current->left, data);
}
return 0;
}
void inorderTraversal(BST* root)
{
if(root == NULL)
cout << "No node" << endl;
inorderTraversal(root->left);
cout << root->data << endl;
inorderTraversal(root->right);
}
int main(){
BST* tree = init(5);
int a[8] = {1, 3, 5, 6, 3, 9, 10, 46};
cout << "seg fault" << endl;
for (unsigned int i = 0; i < sizeof(a); i++)
insert(tree, a[i]);
cout << "seg fault here" << endl;
}
Actually, I think the problem is in your for loop. You are looping too far. Try using a.size() instead of sizeof(a). With sizeof(a) you are requesting the size of the array in bytes, which is probably returning 32.