548 - Tree

All about problems in Volume 5. If there is a thread about your problem, please use it. If not, create one with its number in the subject.

Moderator: Board moderators

vinit_iiita
New poster
Posts: 30
Joined: Mon Jun 19, 2006 10:37 pm
Contact:

Post by vinit_iiita »

Code: Select all

#include<iostream>
#include<sstream>
#include<vector>
using namespace std;
#define vi vector<int>
#define sz size()
#define pb push_back
#define imax 100000001;
struct node{
       int data;
       struct node* left;
       struct node* right;
       };
struct node* rec(vi in,vi p)
{
       if (in.sz==0)
       return NULL;
       int t;
       bool flag=true;
       for (int i=p.sz-1;i>=0 && flag;i--)
       for (t=0;t<in.sz;t++)
       if (p[i]==in[t])
       {
           flag=false;
           break;
           }
       vi in1,in2;
       for (int i=0;i<t;i++)
       in1.pb(in[i]);
       for (int i=t+1;i<in.sz;i++)
       in2.pb(in[i]);
       struct node* tmp =new node;
       tmp->data=in[t];
     //  cout<<tmp->data<<endl;
       tmp->left=rec(in1,p);
       tmp->right=rec(in2,p);
       return tmp;
       }  
int maxi;
int m,l;         
void preorder(struct node* root)
{
    
 //    if (root==NULL)
 //    m=0;  
     if (root!=NULL)
     {
      
         m=m+root->data;
         if (m<=maxi)
         {
         if (root->right==NULL && root->left!=NULL)
         preorder(root->left);
         else if(root->left==NULL && root->right!=NULL)
         preorder(root->right);
         else if (root->right!=NULL && root->left!=NULL)
         {
              preorder(root->left);
              preorder(root->right);
              
              }
     else if (root->left==NULL && root->right==NULL)
     {
      //cout<<"sss\n";
       if (m<maxi)
       {
                  maxi=m;
              //    cout<<"max : "<<maxi<<endl;
                  l=root->data;
                  }
       if(m==maxi && (root->data)<l)
       {
            l=root->data;
            //cout<<"max : "<<m<<endl;
            //cout<<"l : "<<l<<endl;
            }
      
       }
       }
        m=m-root->data;
       }
       }
int main()
{
    string in,post;
    while (getline(cin,in) && getline(cin,post))
    {
          vector<int> io,p;
          istringstream iss(in);
          char a[6];
          string str;
          while (iss>>str)
          {
                for (int i=0;i<str.size();i++)
                a[i]=str[i];
                a[str.size()]='\0';
                int t;
                t=atoi(a);
                io.push_back(t);
                }
           istringstream ins(post);
          while (ins>>str)
          {
                for (int i=0;i<str.size();i++)
                a[i]=str[i];
                a[str.size()]='\0';
                int t;
                t=atoi(a);
                p.push_back(t);
                }   
                m=0;l=10001; maxi=imax;     
        
          struct node *root;
        root=rec(io,p);
  
        preorder(root);
  
          cout<<l<<endl;
          }
 
          return 0;
          }
why TLE :roll: its hopeless...........
win
pradeepr
New poster
Posts: 21
Joined: Fri May 25, 2007 11:52 am
Location: India

TLE!! .. please help me out

Post by pradeepr »

I did exactly wht xenon said(not constructing a tree ,but using a similar one to do dfs ..) but I am still getting TLE!!...
so can some one help me out....this is my code

Code: Select all

#include<iostream>
#include<vector>
#include<cstdlib>
#include<cstdio>
#include<cstring>
using namespace std;
void leastleave(vector<int> inorder,vector<int> postorder,long long &maxsum,int &leaf,int sum,int inleft,int inright,int postleft, int postright)
{
        int size=inright-inleft+1;
        if(inleft >inright)
                return;
        else if(size==1)
        {
                if((sum+inorder[inleft])<maxsum)
                {
                        maxsum=sum+inorder[inleft];
                        leaf=inorder[inleft];
                }
                else if((sum+inorder[inleft])==maxsum)
                {
                        if(inorder[inleft]<leaf)
                                leaf=inorder[inleft];
                }
        }
        else
        {
                int temp=postorder[postright];
                int i=inleft;
                while(inorder[i]!=temp)
                        i++;
                leastleave(inorder,postorder,maxsum,leaf,sum+temp,inleft,i-1,postleft,postleft+i-1-inleft);
                leastleave(inorder,postorder,maxsum,leaf,sum+temp,i+1,inright,postleft+i-inleft,postright-1);
        }
}

int main()
{
        string s;
        string temp;
        while(getline(cin,s))
        {
                long long maxsum=100000000;
                int leaf=0;
                vector<int > inorder,postorder;
                while(1)
                {
                 int i=s.find(" ",0);
                         if(i!=string::npos)
                         {
                                temp=s.substr(0,i);
                                inorder.push_back(atoi(temp.c_str()));
                                s=s.substr(i+1);
                        }
                        else
                        {
                                inorder.push_back(atoi(s.c_str()));
                                   break;
                        }

                }
                getline(cin,s);
                while(1)
                {
                 int i=s.find(" ",0);
                         if(i!=string::npos)
                         {
                                temp=s.substr(0,i);
                                postorder.push_back(atoi(temp.c_str()));
                                s=s.substr(i+1);
                        }
                        else
                        {
                                postorder.push_back(atoi(s.c_str()));
                               break;
                        }

                }
                int size=postorder.size();
                leastleave(inorder,postorder,maxsum,leaf,0,0,size-1,0,size-1);
                cout<<leaf<<'\n';
        }
        return(0);
}
thanks in advance..
x140l31
Learning poster
Posts: 69
Joined: Tue Jan 30, 2007 12:51 am

Re:

Post by x140l31 »

Raiyan Kamal wrote:
INPUT :

3 2 1 4 5 7 6
3 1 2 5 6 7 4
7 8 11 3 5 16 12 18
8 3 11 7 16 18 12 5
255
255
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 22
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 22
7 2 8 10 6 1 11 15 3 4
7 8 6 10 2 15 11 4 3 1
7 5 6 4 8 2 9 1 3 11 10 12
7 6 5 8 4 9 2 11 12 10 3 1
4 2 6 5 7 1 9 3 13 12 8 11
4 6 7 5 2 9 13 12 11 8 3 1


OUTPUT:

1
3
255
1
4
9
4
All values will be different, greater than zero and less than 10000
DD
Experienced poster
Posts: 145
Joined: Thu Aug 14, 2003 8:42 am
Location: Mountain View, California
Contact:

Re: 548 getting TLE

Post by DD »

To vinit_iiita and pradeepr:


If your programs can pass the sample test cases and the other test case listed in this forum, I suggest that the main reason of T.L.E. is due to that the construction of tree are not efficient enough, and you should try to speed up this part.
Have you ever...
  • Wanted to work at best companies?
  • Struggled with interview problems that could be solved in 15 minutes?
  • Wished you could study real-world problems?
If so, you need to read Elements of Programming Interviews.
zhangfei
New poster
Posts: 5
Joined: Thu Jul 29, 2010 2:08 pm

Re: 548 getting TLE

Post by zhangfei »

I got a RE , because I just use a string that has 11,000 elements. The problem says: there are 10,000 nodes .So your string may has 6 times elements.
arrubyyan
New poster
Posts: 1
Joined: Mon Jul 25, 2011 8:11 am

Re: 548 getting TLE

Post by arrubyyan »

I don't know where is my problem, I've got Almost 15 wrongs!! :D can anybody pleeeaaaaaaaasssssse help me?!

Code: Select all

//
//  main.cpp
//  548 - Tree
//
//  Created by Aryan Yaghoubian on 7/24/11.
//  Copyright 2011 Home. All rights reserved.
//

#include <iostream>
#include <string.h>
#include <stdio.h>
#include <vector>
using namespace std;


vector< long long int>::iterator it;
     long long int mins=0;
     long long int minsi=0;

struct Node {
     long long int key;
    Node *lc,*rc,*p;
};
Node *root;
Node* makeTree(vector< long long int> inorder,vector< long long int> postorder,Node *node)
{
    
    if (inorder.empty()) 
    {
        return NULL;
    }
    
    vector< long long int> v1,v2,v3,v4;
     long long int key=postorder.back();
    postorder.pop_back();
    if (node==NULL) {
        node=new Node;
        node->key=key;
        node->lc=node->rc=node->p=NULL;
    }
  
    
     long long int pos=0;
    it=inorder.begin();
    while (*it!=key) {
        it++;
        pos++;
    }
    inorder.erase(it);
    
    for ( long long int i=0; i<pos; i++)
    {
        v1.push_back(inorder[i]);
        v3.push_back(postorder[i]);
    }
    for ( long long int i=pos; i<inorder.size(); i++) {
        v2.push_back(inorder[i]);
        
    }
    for ( long long int i=pos; i<postorder.size(); i++)
    {
        v4.push_back(postorder[i]);
    }
    
    node->lc= makeTree(v1, v3,node->lc);
    node->rc=  makeTree(v2, v4,node->rc);
    if (node->rc!=NULL) {
        node->rc->p=node;
    }
    if (node->lc!=NULL) {
        node->lc->p=node;
    }
    
    return node;
    
}
 long long int rootToLeafSum(Node *node, long long int sum)
{
    
    if(node==NULL)
        return 0;
    
    return node->key + rootToLeafSum(node->p, sum);
    
}

void findLeaves(Node *node)
{
    if (node==NULL) {
        return;
    }
    findLeaves(node->lc);
    if (node->lc==node->rc && node->rc==NULL)
    {
         long long int sum=0;
        sum=rootToLeafSum(node, 0);
        if (sum<mins) {
            mins=sum;
            minsi=node->key;
        }
        if (sum==mins && node->key<minsi) {
            minsi=node->key;
        }        
    }
    findLeaves(node->rc);
}

 int main ()
{
    
         long long int n;
    char s[5000];
    while (cin.getline(s, 5000))
    {
        root=NULL;
       
        minsi=mins=200000000;
        
        
        vector< long long int> inor,postor;
        inor.clear();
        postor.clear();
        
        sscanf(s, "%d",&n);
        inor.push_back(n);
        for (     long long int i=0; i<strlen(s); i++)
        {
            if (s[i]==' ') {
                sscanf(s+i, "%d",&n);
                inor.push_back(n);
            }
        }
        
        
        cin.getline(s, 5000);
        sscanf(s, "%d",&n);
        postor.push_back(n);
        for ( long long int i=0; i<strlen(s); i++)
        {
            if (s[i]==' ') {
                sscanf(s+i, "%d",&n);
                postor.push_back(n);
            }
        }
        
        //        for (it; it<postorder.end(); it++) {
        //            cout<<*it<<" " ;
        //        }
        
       root= makeTree(inor,postor,root);
        
        findLeaves(root);
       // cout<<minsi<<"\n";
        cout<<minsi<<"\n";
        
    }
    
    
    
    return 0;
}


mashaheer
New poster
Posts: 4
Joined: Sat Nov 20, 2010 2:23 pm

Re: 548 getting TLE

Post by mashaheer »

hi all.
i am getting RE and i dont know why.i have made many change in my code but nothing changed...

Code: Select all

#include <iostream>
#include <vector>
#include <cstring>
#include <cstdlib>
#include  <cstdio>
#include <climits>
using namespace std;
int inord[10005];
int level [20010]={0};
char in[1000000];
vector<int> res;
    char str[6]={'\0'};
    int x;
    vector<int>inorder,postorder;
int t_min=0,mini=INT_MAX,answer,m=0;

    int preindex;
void create(vector<int> post,vector<int> in,int s,int e,int i)
{
    int inindex;
    if(s>e)
    return;
    level[i]=post[preindex--];
    if(s==e)
    {
        return ;
    }
    inindex=inord[level[i]];
    create(post, in, inindex+1, e,(2*i)+1);
    create(post, in, s, inindex -1,2*i);
    return ;

}
void get_min(int i)
{
    if(i>m) m=i;
    if(level[i]==0)
        return;
    res.push_back(level[i]);
    t_min+=level[i];
    if(level[2*i]==0 && level[(2*i)+1]==0)
    {
        if(t_min<=mini)
        {
            if(t_min==mini)
            {
                if(answer>res[res.size()-1])
                    answer=res[res.size()-1];
            }
            else
                answer=res[res.size()-1];
            mini=t_min;
        }
            t_min-=res[res.size()-1];
            res.pop_back();
            return;
    }
    get_min(2*i);
    get_min((2*i)+1);
    t_min-=res[res.size()-1];
    res.pop_back();

}
int main()
{
    //freopen("in.txt","r",stdin);
        int z=0;
        int j=0;

    while(gets(in))
    {
        z=j=0;
        for(int i=0;i<strlen(in);i++)
        {
            if(in[i]!=' ')
                str[j++]=in[i];
            else
            {
                x=atoi(str);
                inorder.push_back(x);
                inord[x]=z++;
                memset(str,'\0',strlen(str));
                j=0;
            }

        }

        inorder.push_back(atoi(str));
        inord[atoi(str)]=z;
        memset(str,'\0',strlen(str));
        for(int k=0;k<inorder.size();k++)
        {
            cin>>x;
            postorder.push_back(x);
        }
        getchar();
        preindex=inorder.size()-1;

        create(postorder,inorder,0,inorder.size()-1,1);

        get_min(1);

        cout<<answer<<endl;
        memset(level,0,(m*4)+4);
        answer=m=0;
        postorder.clear();
        inorder.clear();
        res.clear();
        t_min=0;
        mini=INT_MAX;


    }


          return 0;
}
iceman126
New poster
Posts: 5
Joined: Tue Feb 07, 2012 9:13 pm

548 got WA

Post by iceman126 »

I have tried many input/ouputs and every result is correct, but I keeps get WA from the judge.

I used C++ strings to get input and used stringstream to covert string to int.
I construct a tree first, find the sum by dfs, and search for the least terminal node when have many same least sum.

Can someone tell me where my code is wrong??

Code: Select all

#include <iostream>
#include <string>
#include <sstream>

using namespace std;

class Node
{
public:
	int value;
	Node * left, * right;
};
class Anstype
{
public:
	int sum;
	int leaf_value;
};

const int MAX = 10005;
const int MAX_ANS = 2000;
int inorder[MAX];
int postorder[MAX];
Anstype ans[MAX_ANS];
int least[MAX_ANS];
int ans_count;
Node * root;
Node * now;
int is_root;
int mark_pos;

void construct_tree(int in_start, int in_end, int post_start, int post_end, char w);
void dfs(Node *u, int psum);
void delete_node(Node *u);

int main()
{
	string s;
	stringstream ss;
	while (getline(cin, s))
	{
		int num_count = 0;							
		ss.str(s);
		while (!ss.eof())
			ss >> inorder[num_count++];
		num_count = 0;
		getline (cin, s);
		ss.clear();
		ss.str(s);
		while (!ss.eof())
			ss >> postorder[num_count++];
		ss.clear();
		for (int i = 0; i < num_count; i++)
		{
			if (inorder[i] == postorder[num_count-1])
			{
				mark_pos = i;
				break;
			}
		}
		is_root = 1;
		construct_tree(0, num_count-1, 0, num_count-1, 'n');
		ans_count = 0;
		dfs(root, 0);
		int least_count = 0;

		int min = ans[0].sum;
		for (int i = 1; i < ans_count; i++)
			if (ans[i].sum < min)
				min = ans[i].sum;
		for (int i = 0; i < ans_count; i++)
			if (ans[i].sum == min)
				least[least_count++] = ans[i].leaf_value;
		min = least[0];
		for (int i = 1; i < least_count; i++)
			if (least[i] < min)
				min = least[i];
		cout << min << endl;
		delete_node(root);
	}
	return 0;
}

void construct_tree(int in_start, int in_end, int post_start, int post_end, char w)
{
	Node * u = new Node;
	u->value = postorder[post_end];
	u->left = u->right = NULL;
	if (is_root == 1)
	{
		now = root = u;
		is_root = 0;
	}
	else
	{
		if (w == 'r')
		{
			now->right = u;
			now = now->right;
		}
		else if (w == 'l')
		{
			now->left = u;
			now = now->left;
		}
	}
	int pos;
	for (int i = in_start; i <= in_end; i++)
	{
		if (inorder[i] == postorder[post_end])
		{
			pos = i;
			break;
		}
	}

	if (pos-1 == in_start)
	{
		Node * u = new Node;
		u->value = inorder[in_start];
		u->left = u->right = NULL;
		now->left = u;
	}

	if (pos+1 == in_end)
	{
		Node * u = new Node;
		u->value = inorder[in_end];
		u->left = u->right = NULL;
		now->right = u;
	}

	if (in_start < pos-1)
		construct_tree(in_start, pos-1, post_start, pos-1, 'l');			
	if (pos == mark_pos)
		now = root;
	if (pos+1 < in_end)
		construct_tree(pos+1, in_end, pos, post_end-1, 'r');				
}

void dfs(Node *u, int psum)					
{
	static int min_sum;
	int sum;
	sum = psum + u->value;
	if (u->left == NULL && u->right == NULL)
	{
		if (ans_count == 0)
		{
			min_sum = sum;
			ans[ans_count].sum = sum;
			ans[ans_count].leaf_value = u->value;
			ans_count++;
		}
		if (sum < min_sum)
		{
			min_sum = sum;
			ans_count = 0;
			ans[ans_count].sum = sum;
			ans[ans_count].leaf_value = u->value;
			ans_count++;
		}
		else if (sum == min_sum)
		{
			ans[ans_count].sum = sum;
			ans[ans_count].leaf_value = u->value;
			ans_count++;
		}
		return;
	}
	if (u->left != NULL)
		dfs(u->left, sum);
	if (u->right != NULL)
		dfs(u->right, sum);
}

void delete_node(Node *u)
{
	if (u->left != NULL)
		delete_node(u->left);
	if (u->right != NULL)
		delete_node(u->right);
	delete(u);
}
JohnTortugo
New poster
Posts: 18
Joined: Sun Jul 20, 2008 7:05 pm

Re: 548 getting TLE

Post by JohnTortugo »

A few inputs:

Input:

Code: Select all

6 1 2 3 5 4
6 1 5 3 2 4
1000 3000 2000 4000 6000 5000 7000
1000 2000 3000 6000 7000 5000 4000
1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
7000 8000 9000 9500 3000
7000 8000 3000 9500 9000
Output:

Code: Select all

6
1000
1000
3000
Post Reply

Return to “Volume 5 (500-599)”