Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
A complete binary tree with a maximum depth of 16 is known, with all leaf nodes having the same depth. If a small ball is placed at the root node, the ball will begin to fall along the root node. There is a switch on each node in the complete binary tree. The default is all off. When the ball falls, the state of the switch changes whenever a ball falls on a switch. When the ball reaches a node, if the switch on the node is closed, go to the left to go to the ball, otherwise go to the right until it reaches the leaf node. Please help me find the leaf node number after the 12345th ball fell.
You can simulate the given problem and notice that the leaf node at which the ball ends tends to repeat itself after a point of time. For example, for a binary tree of depth 3, the leaf nodes at which the ball ends for multiple roll of the balls are 1 3 2 4 1 3 2 4 1 3 2 4 . . . (assuming the leaf nodes are numbered starting from 1). As visible, the sequence of length 23-1 = 4 keeps repeating itself. We can store this sequence in an array and answer the query for any nth ball throw by looking up the entry corresponding to the n mod 2depth-1 index in this array.
Since our depth is upto 16, the total number of operations required to generate the recurring sequence is 216-1 * 16 = 524288 operations.
Sharing the code for the same https://ideone.com/uuNV2g
#include <iostream>
#include <map>
#include <vector>
using namespace std;
map<int, bool> states; // default value is False
int MAX_DEPTH = 16;
int dfs(int cur, int depth = 0) {
if(depth == MAX_DEPTH) {
return cur - (1<<MAX_DEPTH) + 1;
}
if(states[cur] == 0) {
states[cur] = !states[cur];
return dfs(2*cur, depth+1);
}
else {
states[cur] = !states[cur];
return dfs(2*cur+1, depth+1);
}
}
int main() {
int until = (1LL<<(MAX_DEPTH-1));
vector<int> pos; // 0 indexed
for(int i = 1; i <= until; i++) {
// cout << dfs(1) << ' ';
pos.push_back(dfs(1));
}
cout << pos[(12344%until)];
// 12344 instead of 12345 since the sequence is 0 indexed
}
Hope it works out.
Related
Problem link: UVa 539 - The Settlers of Catan
(UVa website occasionally becomes down. Alternatively, you can read the problem statement pdf here: UVa External 539 - The Settlers of Catan)
This problem gives a small general graph and asks to find the longest road. The longest road is defined as the longest path within the network that doesn’t use an edge twice. Nodes may be visited more than once, though.
Input Constraints:
1. Number of nodes: n (2 <= n <= 25)
2. Number of edges m (1 <= m <= 25)
3. Edges are un-directed.
4. Nodes have degrees of three or less.
5. The network is not necessarily connected.
Input is given in the format:
15 16
0 2
1 2
2 3
3 4
3 5
4 6
5 7
6 8
7 8
7 9
8 10
9 11
10 12
11 12
10 13
12 14
The first two lines gives the number of nodes n and the number of edges m for this test case respectively. The next m lines describe the m edges. Each edge is given by the numbers of the two nodes connected by it. Nodes are numbered from 0 to n - 1.
The above test can be visualized by the following picture:
Now I know that finding the longest path in a general graph is NP-hard. But as the number of nodes and edges in this problem is small and there's a degree bound of each node, a brute force solution (recursive backtracking) will be able to find the longest path in the given time limit (3.0 seconds).
My strategy to solve the problem was the following:
1. Run DFS (Depth First Search) from each node as the graph can be disconnected
2. When a node visits its neighbor, and that neighbor visits its neighbor and so on, mark the edges as used so that no edge can be used twice in the process
3. When the DFS routine starts to come back to the node from where it began, mark the edges as unused in the unrolling process
4. In each step, update the longest path length
My implementation in C++:
#include <iostream>
#include <vector>
// this function adds an edge to adjacency matrix
// we use this function to build the graph
void addEdgeToGraph(std::vector<std::vector<int>> &graph, int a, int b){
graph[a].emplace_back(b);
graph[b].emplace_back(a); // undirected graph
}
// returns true if the edge between a and b has already been used
bool isEdgeUsed(int a, int b, const std::vector<std::vector<char>> &edges){
return edges[a][b] == '1' || edges[b][a] == '1'; // undirected graph, (a,b) and (b,a) are both valid edges
}
// this function incrementally marks edges when "dfs" routine is called recursively
void markEdgeAsUsed(int a, int b, std::vector<std::vector<char>> &edges){
edges[a][b] = '1';
edges[b][a] = '1'; // order doesn't matter, the edge can be taken in any order [(a,b) or (b,a)]
}
// this function removes edge when a node has processed all its neighbors
// this lets us to reuse this edge in the future to find newer (and perhaps longer) paths
void unmarkEdge(int a, int b, std::vector<std::vector<char>> &edges){
edges[a][b] = '0';
edges[b][a] = '0';
}
int dfs(const std::vector<std::vector<int>> &graph, std::vector<std::vector<char>> &edges, int current_node, int current_length = 0){
int pathLength = -1;
for(int i = 0 ; i < graph[current_node].size() ; ++i){
int neighbor = graph[current_node][i];
if(!isEdgeUsed(current_node, neighbor, edges)){
markEdgeAsUsed(current_node, neighbor, edges);
int ret = dfs(graph, edges, neighbor, current_length + 1);
pathLength = std::max(pathLength, ret);
unmarkEdge(current_node, neighbor, edges);
}
}
return std::max(pathLength, current_length);
}
int dfsFull(const std::vector<std::vector<int>> &graph){
int longest_path = -1;
for(int node = 0 ; node < graph.size() ; ++node){
std::vector<std::vector<char>> edges(graph.size(), std::vector<char>(graph.size(), '0'));
int pathLength = dfs(graph, edges, node);
longest_path = std::max(longest_path, pathLength);
}
return longest_path;
}
int main(int argc, char const *argv[])
{
int n,m;
while(std::cin >> n >> m){
if(!n && !m) break;
std::vector<std::vector<int>> graph(n);
for(int i = 0 ; i < m ; ++i){
int a,b;
std::cin >> a >> b;
addEdgeToGraph(graph, a, b);
}
std::cout << dfsFull(graph) << '\n';
}
return 0;
}
I was ordering what is the worst case for this problem? (I'm wondering it should be n = 25 and m = 25) and in the worst case in total how many times the edges will be traversed? For example for the following test case with 3 nodes and 2 edges:
3 2
0 1
1 2
The dfs routine will be called 3 times, and each time 2 edges will be visited. So in total the edges will be visited 2 x 3 = 6 times. Is there any way to find the upper bound of total edge traversal in the worst case?
Suppose I have a binary search tree in which I'm supposed to insert N unique-numbered keys in the order given to me on standard input, then I am to delete all nodes with keys in interval I = [min,max] and also all connections adjacent to these nodes. This gives me a lot of smaller trees that I am to merge together in a particular way. More precise description of the problem:
Given a BST, which contains distinct keys, and interval I, the interval deletion works in two phases. During the first phase it removes all nodes whose key is in I and all edges adjacent to the removed nodes. Let the resulting graph contain k connected components T1,...,Tk. Each of the components is a BST where the root is the node with the smallest depth among all nodes of this component in the original BST. We assume that the sequence of trees Ti is sorted so that for each i < j all keys in Ti are smaller than keys in Tj. During the second phase, trees Ti are merged together to form one BST. We denote this operation by Merge(T1,...,Tk). Its output is defined recurrently as follows:
EDIT: I am also supposed to delete any edge that connects nodes, that are separated by the given interval, meaning in example 2 the edge connecting nodes 10 and 20 is deleted because the interval[13,15] is 'in between them' thus separating them.
For an empty sequence of trees, Merge() gives an empty BST.
For a one-element sequence containing a tree T, Merge(T) = T.
For a sequence of trees T1,...,Tk where k > 1, let A1< A2< ... < An be the sequence of keys stored in the union of all trees T1,...,Tk, sorted in ascending order. Moreover, let m = ⌊(1+k)/2⌋ and let Ts be the tree which contains Am. Then, Merge(T1,...,Tk) gives a tree T created by merging three trees Ts, TL = Merge(T1,...,Ts-1) and TR = Merge(Ts+1,...,Tk). These trees are merged by establishing the following two links: TL is appended as the left subtree of the node storing the minimal key of Ts and TR is appended as the right subtree of the node storing the maximal key of Ts.
After I do this my task is to find the depth D of the resulting merged tree and the number of nodes in depth D-1. My program should be finished in few seconds even for a tree of 100000s of nodes (4th example).
My problem is that I haven't got a clue on how to do this or where even start. I managed to construct the desired tree before deletion but that's about that.
I'd be grateful for implementation of a program to solve this or any advice at all. Preferably in some C-ish programming language.
examples:
input(first number is number of keys to be inserted in the empty tree, the second are the unique keys to be inserted in the order given, the third line containts two numbers meaning the interval to be deleted):
13
10 5 8 6 9 7 20 15 22 13 17 16 18
8 16
correct output of the program: 3 3 , first number being the depth D, the second number of nodes in depth D-1
input:
13
10 5 8 6 9 7 20 15 22 13 17 16 18
13 15
correct output: 4 3
pictures of the two examples
example 3: https://justpaste.it/1du6l
correct output: 13 6
example 4: link
correct output: 58 9
This is a big answer, I'll talk at high-level.Please examine the source for details, or ask in comment for clarification.
Global Variables :
vector<Node*> roots : To store roots of all new trees.
map<Node*,int> smap : for each new tree, stores it's size
vector<int> prefix : prefix sum of roots vector, for easy binary search in merge
Functions:
inorder : find size of a BST (all calls combinedly O(N))
delInterval : Main theme is,if root isn't within interval, both of it's childs might be roots of new trees. The last two if checks for that special edge in your edit. Do this for every node, post-order. (O(N))
merge : Merge all new roots positioned at start to end index in roots. First we find the total members of new tree in total (using prefix-sum of roots i.e prefix). mid denotes m in your question. ind is the index of root that contains mid-th node, we retrieve that in root variable. Now recursively build left/right subtree and add them in left/right most node. O(N) complexity.
traverse: in level map, compute the number of nodes for every depth of tree. (O(N.logN), unordered_map will turn it O(N))
Now the code (Don't panic!!!):
#include <bits/stdc++.h>
using namespace std;
int N = 12;
struct Node
{
Node* parent=NULL,*left=NULL,*right = NULL;
int value;
Node(int x,Node* par=NULL) {value = x;parent = par;}
};
void insert(Node* root,int x){
if(x<root->value){
if(root->left) insert(root->left,x);
else root->left = new Node(x,root);
}
else{
if(root->right) insert(root->right,x);
else root->right = new Node(x,root);
}
}
int inorder(Node* root){
if(root==NULL) return 0;
int l = inorder(root->left);
return l+1+inorder(root->right);
}
vector<Node*> roots;
map<Node*,int> smap;
vector<int> prefix;
Node* delInterval(Node* root,int x,int y){
if(root==NULL) return NULL;
root->left = delInterval(root->left,x,y);
root->right = delInterval(root->right,x,y);
if(root->value<=y && root->value>=x){
if(root->left) roots.push_back(root->left);
if(root->right) roots.push_back(root->right);
return NULL;
}
if(root->value<x && root->right && root->right->value>y) {
roots.push_back(root->right);
root->right = NULL;
}
if(root->value>y && root->left && root->left->value<x) {
roots.push_back(root->left);
root->left = NULL;
}
return root;
}
Node* merge(int start,int end){
if(start>end) return NULL;
if(start==end) return roots[start];
int total = prefix[end] - (start>0?prefix[start-1]:0);//make sure u get this line
int mid = (total+1)/2 + (start>0?prefix[start-1]:0); //or this won't make sense
int ind = lower_bound(prefix.begin(),prefix.end(),mid) - prefix.begin();
Node* root = roots[ind];
Node* TL = merge(start,ind-1);
Node* TR = merge(ind+1,end);
Node* temp = root;
while(temp->left) temp = temp->left;
temp->left = TL;
temp = root;
while(temp->right) temp = temp->right;
temp->right = TR;
return root;
}
void traverse(Node* root,int depth,map<int, int>& level){
if(!root) return;
level[depth]++;
traverse(root->left,depth+1,level);
traverse(root->right,depth+1,level);
}
int main(){
srand(time(NULL));
cin>>N;
int* arr = new int[N],start,end;
for(int i=0;i<N;i++) cin>>arr[i];
cin>>start>>end;
Node* tree = new Node(arr[0]); //Building initial tree
for(int i=1;i<N;i++) {insert(tree,arr[i]);}
Node* x = delInterval(tree,start,end); //deleting the interval
if(x) roots.push_back(x);
//sort the disconnected roots, and find their size
sort(roots.begin(),roots.end(),[](Node* r,Node* v){return r->value<v->value;});
for(auto& r:roots) {smap[r] = inorder(r);}
prefix.resize(roots.size()); //prefix sum root sizes, to cheaply find 'root' in merge
prefix[0] = smap[roots[0]];
for(int i=1;i<roots.size();i++) prefix[i]= smap[roots[i]]+prefix[i-1];
Node* root = merge(0,roots.size()-1); //merge all trees
map<int, int> level; //key=depth, value = no of nodes in depth
traverse(root,0,level); //find number of nodes in each depth
int depth = level.rbegin()->first; //access last element's key i.e total depth
int at_depth_1 = level[depth-1]; //no of nodes before
cout<<depth<<" "<<at_depth_1<<endl; //hoorray
return 0;
}
I did search and looked at these below links but it didn't help .
Point covering problem
Segments poked (covered) with points - any tricky test cases?
Need effective greedy for covering a line segment
Problem Description:
You are given a set of segments on a line and your goal is to mark as
few points on a line as possible so that each segment contains at least
one marked point
Task.
Given a set of n segments {[a0,b0],[a1,b1]....[an-1,bn-1]} with integer
coordinates on a line, find the minimum number 'm' of points such that
each segment contains at least one point .That is, find a set of
integers X of the minimum size such that for any segment [ai,bi] there
is a point x belongs X such that ai <= x <= bi
Output Description:
Output the minimum number m of points on the first line and the integer
coordinates of m points (separated by spaces) on the second line
Sample Input - I
3
1 3
2 5
3 6
Output - I
1
3
Sample Input - II
4
4 7
1 3
2 5
5 6
Output - II
2
3 6
I didn't understand the question itself. I need the explanation, on how to solve this above problem, but i don't want the code. Examples would be greatly helpful
Maybe this formulation of the problem will be easier to understand. You have n people who can each tolerate a different range of temperatures [ai, bi]. You want to find the minimum number of rooms to make them all happy, i.e. you can set each room to a certain temperature so that each person can find a room within his/her temperature range.
As for how to solve the problem, you said you didn't want code, so I'll just roughly describe an approach. Think about the coldest room you have. If making it one degree warmer won't cause anyone to no longer be able to tolerate that room, you might as well make the increase, since that can only allow more people to use that room. So the first temperature you should set is the warmest one that the most cold-loving person can still tolerate. In other words, it should be the smallest of the bi. Now this room will satisfy some subset of your people, so you can remove them from consideration. Then repeat the process on the remaining people.
Now, to implement this efficiently, you might not want to literally do what I said above. I suggest sorting the people according to bi first, and for the ith person, try to use an existing room to satisfy them. If you can't, try to create a new one with the highest temperature possible to satisfy them, which is bi.
Yes the description is pretty vague and the only meaning that makes sense to me is this:
You got some line
Segment on a line is defined by l,r
Where one parameter is distance from start of line and second is the segments length. Which one is which is hard to tell as the letters are not very usual for such description. My bet is:
l length of segment
r distance of (start?) of segment from start of line
You want to find min set of points
So that each segment has at least one point in it. That mean for 2 overlapped segments you need just one point ...
Surely there are more option how to solve this, the obvious is genere & test with some heuristics like genere combinations only for segments that are overlapped more then once. So I would attack this task in this manner (using assumed terminology from #2):
sort segments by r
add number of overlaps to your segment set data
so the segment will be { r,l,n } and set the n=0 for all segments for now.
scan segments for overlaps
something like
for (i=0;i<segments;i++) // loop all segments
for (j=i+1;j<segments;j++) // loop all latter segments until they are still overlapped
if ( segment[i] and segment [j] are overlapped )
{
segment[i].n++; // update overlap counters
segment[j].n++;
}
else break;
Now if the r-sorted segments are overlapped then
segment[i].r <=segment[j].r
segment[i].r+segment[i].l>=segment[j].r
scan segments handling non overlapped segments
for each segment such that segment[i].n==0 add to the solution point list its point (middle) defined by distance from start of line.
points.add(segment[i].r+0.5*segment[i].l);
And after that remove segment from the list (or tag it as used or what ever you do for speed boost...).
scan segments that are overlapped just once
So if segment[i].n==1 then you need to determine if it is overlapped with i-1 or i+1. So add the mid point of the overlap to the solution points and remove i segment from list. Then decrement the n of the overlapped segment (i+1 or i-1)` and if zero remove it too.
points.add(0.5*( segment[j].r + min(segment[i].r+segment[i].l , segment[j].r+segment[j].l )));
Loop this whole scanning until there is no new point added to the solution.
now you got only multiple overlaps left
From this point I will be a bit vague for 2 reasons:
I do not have this tested and I d not have any test data to validate not to mention I am lazy.
This smells like assignment so there is some work/fun left for you.
From start I would scann all segments and remove all of them which got any point from the solution inside. This step you should perform after any changes in the solution.
Now you can experiment with generating combination of points for each overlapped group of segments and remember the minimal number of points covering all segments in group. (simply by brute force).
There are more heuristics possible like handling all twice overlapped segments (in similar manner as the single overlaps) but in the end you will have to do brute force on the rest of data ...
[edit1] as you added new info
The r,l means distance of left and right from the start of line. So if you want to convert between the other formulation { r',l' } and (l<=r) then
l=r`
r=r`+l`
and back
r`=l
l`=r-l`
Sorry too lazy to rewrite the whole thing ...
Here is the working solution in C, please refer to it partially and try to fix your code before reading the whole. Happy coding :) Spoiler alert
#include <stdio.h>
#include <stdlib.h>
int cmp_func(const void *ptr_a, const void *ptr_b)
{
const long *a = *(double **)ptr_a;
const long *b = *(double **)ptr_b;
if (a[1] == b[1])
return a[0] - b[0];
return a[1] - b[1];
}
int main()
{
int i, j, n, num_val;
long **arr;
scanf("%d", &n);
long values[n];
arr = malloc(n * sizeof(long *));
for (i = 0; i < n; ++i) {
*(arr + i) = malloc(2 * sizeof(long));
scanf("%ld %ld", &arr[i][0], &arr[i][1]);
}
qsort(arr, n, sizeof(long *), cmp_func);
i = j = 0;
num_val = 0;
while (i < n) {
int skip = 0;
values[num_val] = arr[i][1];
for (j = i + 1; j < n; ++j) {
int condition;
condition = arr[i][1] <= arr[j][1] ? arr[j][0] <= arr[i][1] : 0;
if (condition) {
skip++;
} else {
break;
}
}
num_val++;
i += skip + 1;
}
printf("%d\n", num_val);
for (int k = 0; k < num_val; ++k) {
printf("%ld ", values[k]);
}
free(arr);
return 0;
}
Here's the working code in C++ for anyone searching :)
#include <bits/stdc++.h>
#define ll long long
#define double long double
#define vi vector<int>
#define endl "\n"
#define ff first
#define ss second
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define mp make_pair
using namespace std;
bool cmp(const pair<ll,ll> &a, const pair<ll,ll> &b)
{
return (a.second < b.second);
}
vector<ll> MinSig(vector<pair<ll,ll>>&vec)
{
vector<ll> points;
for(int x=0;x<vec.size()-1;)
{
bool found=false;
points.pb(vec[x].ss);
for(int y=x+1;y<vec.size();y++)
{
if(vec[y].ff>vec[x].ss)
{
x=y;
found=true;
break;
}
}
if(!found)
break;
}
return points;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin>>n;
vector<pair<ll,ll>>v;
for(int x=0;x<n;x++)
{
ll temp1,temp2;
cin>>temp1>>temp2;
v.pb(mp(temp1,temp2));
}
sort(v.begin(),v.end(),cmp);
vector<ll>res=MinSig(v);
cout<<res.size()<<endl;
for(auto it:res)
cout<<it<<" ";
}
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph{
public:
vector<int> adjList[10001];
void addEdge(int u,int v){
adjList[u].push_back(v);
adjList[v].push_back(u);
}
};
bool dfs(Graph graph, int n){
vector<int> neighbors;
int curr,parent;
bool visited[10001] = {0};
stack<int> s;
//Depth First Search
s.push(1);
parent = 0;
while(!s.empty()){
curr = s.top();
neighbors = graph.adjList[curr];
s.pop();
//If current is unvisited
if(visited[curr] == false){
for(int j=0; j<neighbors.size(); j++){
//If node connected to itself, then cycle exists
if(neighbors[j] == curr){
return false;;
}
else if(visited[neighbors[j]] == false){
s.push(neighbors[j]);
}
//If the neighbor is already visited, and it is not a parent, then cycle is detected
else if(visited[neighbors[j]] == true && neighbors[j] != parent){
return false;
}
}
//Mark as visited
visited[curr] = true;
parent = curr;
}
}
//Checking if graph is fully connected
for(int i=1; i<=n; i++){
if(visited[i] == false){
return false;
}
}
//Only if there are no cycles, and it's fully connected, it's a tree
return true;
}
int main() {
int m,n,u,v;
cin>>n>>m;
Graph graph = Graph();
//Build the graph
for(int edge=0; edge<m; edge++){
cin>>u>>v;
graph.addEdge(u,v);
}
if(dfs(graph,n)){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
return 0;
}
I am trying to determine if a given graph is a tree.
I perform DFS and look for cycles, if a cycle is detected, then the given graph is not a tree.
Then I check if all nodes have been visited, if any node is not visited, then given graph is not a tree
The first line of input is:
n m
Then m lines follow, which represent the edges connecting two nodes
n is number of nodes
m is number of edges
example input:
3 2
1 2
2 3
This is a SPOJ question http://www.spoj.com/problems/PT07Y/ and I am getting Wrong Answer. But the DFS seems to be correct according to me.
So I checked your code against some simple test cases in comments, and it seems that for
7 6
3 1
3 2
2 4
2 5
1 6
1 7
you should get YES as answer, while your program gives NO.
This is how neighbours looks like in this case:
1: 3 6 7
2: 3 4 5
3: 1 2
4: 2
5: 2
6: 1
7: 1
So when you visit 1 you push 3,6,7 on the stack. Your parent is set as 1. This is all going good.
You pop 7 from the stack, you don't push anything on the stack and cycle check clears out, so as you exit while loop you set visited[7] as true and set you parent to 7 (!!!!!).
Here is you can see this is not going well, since once you popped 6 from the stack you have 7 saved as parent. And it should be 1. This makes cycle check fail on neighbor[0] != parent.
I'd suggest adding keeping parent in mapped array and detect cycles by applying union-merge.
I have an array suppose {10,1,10,9}
Now I have to a form a binary tree with start node as array[0] which is 10 here, the tree structure will be like this
first element 10
here in the picture, first element is 10, now I have to select left child and right child, so 2nd element is my left child and last element is my right child.
If 1 is my left child then I am having 10 and 9 remaining to process so 10 will be left child and 9 will be the right child for 1 as parent, now for 10 as parent, only 9 is left, so this would be the left child, and so one this tree is building.
I am trying to use recursion which I am little weak and trying to learn,but my code is not working how I am thinking, obviously I am doing somthing wrong, please guide me through this.
#include<iostream>
using namespace std;
int temparr[20];
void calculateMax(int arr[],int start, int end)
{
if(start > end)
return;
cout<<arr[start]<<" ";
calculateMax(arr,start+1,end);
calculateMax(arr,start,end-1);
}
int main()
{
int arr[] = {10,1,10,9};
temparr[0] = 10;
int n = sizeof(arr)/sizeof(int);
calculateMax(arr,0,n-1);
//for(int i=0;i<20;++i)
//cout<<temparr[i]<<" ";
return 0;
}
my cout should output 10 1 10 9 9 10 9 1 10 10 1 but its not.