Quantcast
Channel: CodeChef Discuss - latest questions
Viewing all 39796 articles
Browse latest View live

Data Structure : Linked list

$
0
0

Overview :
Linked List is a linear data structure .It is a collection of nodes.The nodes connect by pointer. Each node is contain two parts. data part, link part

  • Data contains the node value.
  • Link contains the address of next node.

alt text

Advantage of linked list :

  • Dynamic in nature
  • Insertion and deletion can be easily implemented.
  • Reduces the access time.

But here we discuss about the single linked list.

Single linked list Single linked list contain nodes which have a data part as well as address part which points to the next node in sequence of nodes. Before being single linked list operation we need to d

Disadvantage of linked list :

  • Random access is not allowed.
  • Memory is wastage.
  • Reverse traversing is difficult.

Applications of Linked List :

  • It is used to implement stack , queue, , graph etc.
  • Representing sparse matrix.
  • For separate chaining hash-table.

There are three types of linked list

  1. Single Linked List
  2. Double Linked List
  3. Circular Linked List

But here we discuss about Single Linked List. Single linked list contain nodes which have a data part as well as adress part which points to the next node in sequence of nodes.

Before doing Singly Linked operations we need to define structure for Single linked list.

struct node
{
  int data;
  node *next;
}*start=NULL:

Node Creation :
Algorithm : creation(data)

Step 1: Start
Step 2: Set temp =new node
Step 3: Set temp.data = data
Step 4: Set temp.next =NULL
Step 5: Return temp
Step 6: ENd


Traverse :
Algorithm: Traverse()

Step 1: Start
Step 2: Set temp = start
Step 3:while(temp!=NULL)
        print temp.data
        temp = temp.next
Step 4: End


Insertion :

Insertion at First

Algorithm : InserFirst( data)
 Step 1: Start
 Step 2: Set newn = creation(data).
 Step 3:if(start==NULL){ start  = newn; start.next =NULL;}else{ newn.next = start; start = newn;}
 Step 4: End.

Insertion at Middle
Algorithm : InsertMiddle(data,position)

Step 1: Start
Step 2: Set temp = start and newn = creation(data)
Step 3:for i=0 to position-2
        temp = temp.next
Step 4: Set temp1 = temp.next
Step 5: temp.next = newn
Step 6: newn.next = temp1
Step 7: End.


Deletion:

Algorithm : Delete(position)
Step 1: Start
Step 2: Set temp = start
Step 3:if(position==1){if(start==NULL) print deletion not possible.else            start = start.next;free(temp);}else{for i=0 to position-2{
             temp = temp.next;}
            Set temp1  = temp.next;
            temp.next = temp1.nextfree(temp1)}

Step 4: End

Searching

Algorithm :
Search(data)
Step 1: Start
Step 2: Set temp = start, position =0, flag =false.
Step 3: While (temp.next!=NULL)
         position increment;if(temp.data==data){
            flag =true.
            print data is foundbreakwhile loop;}
         temp = temp->next;
Step 4: If flag =false print Not found.
Step 5:End

Full Source Code : link

Hackerrank Problem Problem : Print the Elements of a Linked List, Insert a node at the head of a linked list, Insert a node at a specific position in a linked list, Delete a Node


[Tutorials] Finding Prime Factors in O(sqrt(n))

$
0
0

Hi all,

In this post am going to explain find prime factors in O(sqrt(n)).

Steps

  1. We will reduce the given no to odd no.
  2. After which we will start checking for divisibility from 3 to sqrt(N) while increasing our counter by 2 as we can skip checking for even no's.
  3. At last we check for special condition when n is itself a prime no.

Well you may ask why till sqrt(N)? Let me explain.

Every composite number has at least one prime factor less than or equal to square root of itself.

Want me to prove it? OK let's prove it.

Let a and b be two factors of n such that a*b = n. If both are greater than √n, then a.b > √n, * √n, which contradicts the expression “a * b = n”. Hence its correct.

# include <stdio.h>
 # include <math.h>
 void main()
 {
  int n,s;
  scanf("%d",&n);
   s=sqrt(n);
  // converts n to odd no
  while (n%2 == 0)
  {
    printf("%d ",2);
     n /=2;
   }

//we can skip one element as n is odd now
for (int i=3;i <= sq;i = i+2)
{
    while (n%i ==0)
    {
        printf("%d ",i);
        n /=i;
    }
}

// handles condition when n is itself a prime no
if (n > 2)
    printf ("%d",n);

}

The Best Websites?

$
0
0

Hi Coders!
I would like to know from you all the best website to learn c plus plus

Note:I am not a book reader and i want to learn in free 'n' fun way and i want to learn list,vector,stack,heaps,etc.

Thanks

CodeChef Benefit

$
0
0

Hi!
I saw many website that are not for free.
But why codechef gives us free to learn ,practice & Discuss

Do competive programming allow us submit problems multiple times?

$
0
0

Online judges allow us to submit problems multiple times. But I wonder if in real programming contest(IOI, ACM...), are we allowed to submit problems multiple time, if yes do we get penalized?

Data Structure Tutorial : Tree

$
0
0

Tree
A tree is a non linear data structure . It is a finite collection of nodes that reflects one to many relationship. It is hierarchical structure. The connection line between two nodes is called edge.

 The topmost node is called root of the tree.

 The element that are directly under an element are called its children.

 The element directly above something is called its parent.

 Except the root each element has a parent.

 The node that has child node is called parent node.

 Two nodes that have the same parent are called sibling.**

 A node that is connected to all lower-level nodes is called an ancestor.

 The connected lower-level nodes are descendants of the ancestor node.

 Height of a node is the number of edges between the target node and furthest leaf node.

 Depth  of a node is the number of edges between the target node and root node.

alt text

 Applications of tree:
  1. File system.
  2. Storing hierarchies in organizations
  3. Router algorithms



  Binary Tree: A tree whose elements have at most 2 children is called a binary tree.

alt text Mainly Here we discuss about the Binary Search Tree

  Binary Search Tree :  A Binary Search Tree is a binary tree where all the node value of the left subtree are smaller than or equal to the root node value and the node value of the right subtree are larger than or equal to the root node value.

alt text


Before doing binary search tree we need to define structure for binary search tree.

 struct bst
 {
   int data;
   bst *left;
   bst *right;
 }*root=NULL:

BST Creation :

bst *creation(int data){

  bst *newnode = new bst;newnode->data = data;
   newnode->left= newnode->right =NULL:return newnode;}

Inorder traversal Algorithm:

Inorder(root)
Step 1: Start
Step 2: if root!=NULL
        inorder(root.left);
        print root.data;
        inorder(root.right);
Step 3: End.

C++ implementation: void inorder(bst *root) { if(root!=NULL) { inorder(root->left); cout<<root->data<<" "; inorder(root->right); } }


BST Seach Algorithm:

Search(root,data)
Step 1: Start
Step 2: if (root==NULL)           return false;
        else if(root.data = data) return true
        else if(root.data < data) return search(root.right, data);
        else                      return search(root.left,  data);                                      
Step 3: End

C++ implementation: bool search(bst *root,int data) { if(root==NULL) return root; else if(root->data = data) return true else if(root->data < data) return search(root->right, data); else return search(root->left, data); }


Insertion Algorithm:

Insertion(root,data)
 Step 1: Start
 Step 2:if(root==NULL)             root = creation(data);elseif(root->data < data)  root.right = Insetion(root.right, data);elseif(root->data > data)  root.left  = Insertion(root.left,  data);elsereturn root;
Step 3: End

C++ implementation: bst Insertion(bst root,int data){if(root==NULL) root = creation(data);elseif(root->data < data) root->right = Insetion(root->right, data);elseif(root->data > data) root->left = Insertion(root->left, data);elsereturn root;}

alt text


Function to find minimum in a tree.

bst* FindMin(bst* root){if(root==NULL|| root->left ==NULL)return root;elsereturn FindMin(root->left);}

Deletion Algorithm:

Deletion(root, data)
Step 1: Start
Step 2: Locate the node to be deleted
Step 3:Three Case can be considered
   Case 1 : If the node is leaf node:
       i.If the node is left child of the parent, make NULL the left pointer of its parent node and free the space for the node.
      ii.If the node is right child of the parent, make NULL the right pointer of its parent node and free the space for the node.

   Case 2:  If the node has one child:
      i.If the node to be deleted is left child of its parent, then make link between the left pointer of its parent node and child node(left or right) of the node to be deleted. Then delete the node.
      II.If the node to be deleted is right child of its parent, then make link between the right pointer of its parent node and child node(left or right) of the node to be deleted. Then delete the node.

   Case 3: If the node to be deleted has two children:
       Find the the node with minimum value from the right sub tree (the node to be delete).Replace the node value to be deleted .Delete the target node.

Step 4: ENd.


C++ implementation :

bst *Deletion(bst *root, int data)
 {
   if (root==NULL)                return root;
   else if(root->data > data)     root->left  = Deletion(root->left, data);
   else if(root->data < data)  root->right = Deletion(root->right, data);
   else
   {
        if(root->left==NULL && root->right==NULL)
        {
          delete root;
          root = NULL;
        }


        else if(root->left==NULL)
        {
          bst *temp = root;
          root = root->right;
          delete temp;
        }

        else if(root->right==NULL)
        {
          bst *temp = root;
          root = root->left;
          delete temp;
        }


        else
        {
          bst *temp = FindMin(root->right);
          root->data = temp->data;
          root->right = Deletion(root->right, temp->data);
        }
      }
  }

alt textalt text


Height Of BST : Height Of Binary search tree is the number of edges between the root node and furthest leaf node.alt text

Algorithm : Height(root)
Step 1: Start
Step 2:if (root==NULL) return -1;
      else   return max(getHeight(root.left), getHeight(root.right)) + 1;
Step 3: End

C++ implementation :

int getHeight(Node*root) {
    if(root == NULL) return -1;
    else             return max(getHeight(root->left), getHeight(root->right)) + 1;}


Full Source code : Link

Hackerrank Problem : Binary Search Tree : Insertion, Inorder Traversal, Binary Search Trees

CHFNFRN - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Antoniuk Vasyl
Tester:Praveen Dhinwa
Editorialist:Ajay K. Verma

DIFFICULTY:

Easy

PREREQUISITES:

Graph Complement, Two-coloring.

PROBLEM:

Given a graph G = (V, E), determine, whether its vertices can be partitioned into two sets V1 and V2, such that both V1 and V2 form a clique in G.

QUICK EXPLANATION:

Such a partition is possible, iff the complement of graph G is a bipartite graph.

EXPLANATION:

Suppose for a given graph G = (V, E), we can partition the vertices into two sets V1 and V2, such that both V1 and V2 form a clique in G.

Let us say that H = (V, E') is the complement graph of G, which has the same vertex set as that of G, however an edge (u, v) exists in H iff the edge (u, v) does not exist in G, and vice versa.

Since V1 forms a clique in G (i.e., all vertices of V1 are connected with each other via an edge), it must form an independent set in H (i.e., no two vertices of V1 are connected by an edge in H). The same holds for the set V2.

In other words, the vertex set V can be partitioned into two sets V1 and V2, such that both V1 and V2 form independent set in H. In other words, all edges of H are of the form (u, v), where u belong to the set V1, and v belong to the set V2. In other words, H is a bipartite graph.

Hence, we only need to check whether the graph H is a bipartite graph. This can be done in the linear time (in the number of edges and vertices) using a depth first traversal of the graph as shown here.

TIME COMPLEXITY:

O (N2), where N is the number of vertices in the graph.

Note that the bipartiteness can be checked in linear time, however the complement of input graph may have quadratic number of edges. Hence, the complexity of this method is O (N2).

AUTHOR'S AND TESTER'S SOLUTIONS:

Author's solution
Tester's solution will be uploaded soon.

Why don't we get karma on upvoted comments?

$
0
0

Just like we get for answers why can't we get karma for comments?


Size of the CodeChef Bag!!!

$
0
0

The previous bag of codechef was very small and even a laptop didn't fit into it. I am not saying that it was not good but still it was too small. In the goodies section there is a new bag(red colored). I wanted to ask that is the bag of good size?

Dijkstar's Algo to find shortest path from 1 to N

$
0
0

In The Dijkstra's algo we need to extract the minimum of D where D is the distance from node 0. But as D gets updated with the distance randomly how could we extract the minimum. Eg: Let at an instance we have the below array and we have used the node 0(its distance to itself is always 0) and accordingly its adjacent node2 and node5 get updated with distance from node 0. D: 0 INF 3 INF INF 1 INF

If we use O(n) then ultimately we are using O(n^2) as we will be updating the adjacent of node 5 and again extracting the minimum by using O(n). Is there a better approach to extract the minimum??

ICTAK02-Editorial

$
0
0

Rahul is a unique student; he does everything differently. When he sends a message, he follows a technique. He encodes every character in his message in the following manner: 'a' is send as 'c' 'b' i send as 'd' 'c' is send as 'e' and so on... Find out a solution to automate the above problem:

ICTAK02-Editorial

$
0
0

Rahul is a unique student; he does everything differently. When he sends a message, he follows a technique. He encodes every character in his message in the following manner: 'a' is send as 'c' 'b' i send as 'd' 'c' is send as 'e' and so on... Find out a solution to automate the above problem:

ICTAK01 - Editorial

$
0
0

Given a string 'X' and another string 'y' to be searched. Here 'y' is a substring of 'X'. Find out the the starting position of the string 'y' in it's last occurrence in the string 'X' (The position should be searched including whitespaces). If there is no occurrence or only one occurrence of the given string, the function should return -1.

ZCO: Is it fair??

$
0
0

@all heard about the issues at today's ZCO. Technical Problems.Again?
This is becoming a serious issue now ; IARCS committee has to look into it. This is the past 3 year scenario:
ZCO 2015:
I gave ZCO 2015 and back then also i faced same issues: website crashes, session expired etc. and after the time got over they mail and informed that time has been extended by half an hour. Now who is supposed to look at mail at that point of time. And about the announcement of website:for that the website should have load up. And they thought it was fair.
ZCO 2016:
Last year(ZCO 2016) they granted qualification to all students and thought it was fair.But the question is : Is it really fair for all?
ZCO 2017:
Now this year this will be a serious issue as back at my time one could have opted for ZCO or ZIO inclusively. But this year it is exclusive or. So if they grant qualification to all the ones giving ZCO it will be unfair for the ones who are giving ZIO. If they grant to all what is point of having this at all.

So this is not supposed to go fair. It has been 3 years same issues; Same suggestions of shifting it to some already existing Online Judges:such as codechef. But still no progress. This is to request you all to mail IARCS in as much amount as possible.And if someone here on codechef is in contact with the organizing committee please request them. Because it seems as if they are not at all learning from the past experiences.

codechef should include graph for lunchtime

$
0
0

I think there should be a graph for lunchtime.
so that participant can check there progress.


Dijkstra algorithm - tutorial

$
0
0

Given a graph and a source vertex in graph, find shortest paths from source to all vertices in the given graph.

Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has minimum distance from source.

Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm 1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. 2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. 3) While sptSet doesn’t include all vertices ….a) Pick a vertex u which is not there in sptSetand has minimum distance value. ….b) Include u to sptSet. ….c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v.

Let us understand with the following example:

The set sptSetis initially empty and distances assigned to vertices are {0, INF, INF, INF, INF, INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum distance value. The vertex 0 is picked, include it in sptSet. So sptSet becomes {0}. After including 0 to sptSet, update distance values of its adjacent vertices. Adjacent vertices of 0 are 1 and 7. The distance values of 1 and 7 are updated as 4 and 8. Following subgraph shows vertices and their distance values, only the vertices with finite distance values are shown. The vertices included in SPT are shown in green color.

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET). The vertex 1 is picked and added to sptSet. So sptSet now becomes {0, 1}. Update the distance values of adjacent vertices of 1. The distance value of vertex 2 becomes 12.

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET). Vertex 7 is picked. So sptSet now becomes {0, 1, 7}. Update the distance values of adjacent vertices of 7. The distance value of vertex 6 and 8 becomes finite (15 and 9 respectively).

Pick the vertex with minimum distance value and not already included in SPT (not in sptSET). Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}. Update the distance values of adjacent vertices of 6. The distance value of vertex 5 and 8 are updated.

We repeat the above steps until sptSet doesn’t include all vertices of given graph. Finally, we get the following Shortest Path Tree (SPT).

How to implement the above algorithm? We use a boolean array sptSet[] to represent the set of vertices included in SPT. If a value sptSet[v] is true, then vertex v is included in SPT, otherwise not. Array dist[] is used to store shortest distance values of all vertices.

// A C / C++ program for Dijkstra's single source shortest path algorithm. // The program is for adjacency matrix representation of the graph

include <stdio.h>

include <limits.h>

// Number of vertices in the graph

define V 9

// A utility function to find the vertex with minimum distance value, from // the set of vertices not yet included in shortest path tree int minDistance(int dist[], bool sptSet[]) { // Initialize min value int min = INT_MAX, min_index;

for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v;

return min_index; }

// A utility function to print the constructed distance array int printSolution(int dist[], int n) { printf("Vertex Distance from Source\n"); for (int i = 0; i < V; i++) printf("%d \t\t %d\n", i, dist[i]); }

// Funtion that implements Dijkstra's single source shortest path algorithm // for a graph represented using adjacency matrix representation void dijkstra(int graph[V][V], int src) { int dist[V]; // The output array. dist[i] will hold the shortest // distance from src to i

 bool sptSet[V]; // sptSet[i] will true if vertex i is included in shortest
                 // path tree or shortest distance from src to i is finalized

 // Initialize all distances as INFINITE and stpSet[] as false
 for (int i = 0; i < V; i++)
    dist[i] = INT_MAX, sptSet[i] = false;

 // Distance of source vertex from itself is always 0
 dist[src] = 0;

 // Find shortest path for all vertices
 for (int count = 0; count < V-1; count++)
 {
   // Pick the minimum distance vertex from the set of vertices not
   // yet processed. u is always equal to src in first iteration.
   int u = minDistance(dist, sptSet);

   // Mark the picked vertex as processed
   sptSet[u] = true;

   // Update dist value of the adjacent vertices of the picked vertex.
   for (int v = 0; v < V; v++)

     // Update dist[v] only if is not in sptSet, there is an edge from
     // u to v, and total weight of path from src to  v through u is
     // smaller than current value of dist[v]
     if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX&& dist[u]+graph[u][v] < dist[v])
        dist[v] = dist[u] + graph[u][v];
 }

 // print the constructed distance array
 printSolution(dist, V);

}

// driver program to test above function int main() { / Let us create the example graph discussed above / int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, {4, 0, 8, 0, 0, 0, 0, 11, 0}, {0, 8, 0, 7, 0, 4, 0, 0, 2}, {0, 0, 7, 0, 9, 14, 0, 0, 0}, {0, 0, 0, 9, 0, 10, 0, 0, 0}, {0, 0, 4, 0, 10, 0, 2, 0, 0}, {0, 0, 0, 14, 0, 2, 0, 1, 6}, {8, 11, 0, 0, 0, 0, 1, 0, 7}, {0, 0, 2, 0, 0, 0, 6, 7, 0} };

dijkstra(graph, 0);

return 0;

}

Dijkstra's K shortest path algorithm !!

$
0
0

Can anyone provide me code(C)/algorithm(loopless) for Dijkstra's k shortest path algorithm using matrix convention ??

Given an (unsorted) array of n elements, can we sort them in O(n) time?

$
0
0

Please help me to solve this - Given an (unsorted) array of n elements, can we sort them in O(n) time?

RGAME - Editorial

$
0
0

PROBLEM LINK:

Practice
Contest

Author:Abhra Dasgupta
Tester:Antoniuk Vasyl and Misha Chorniy
Editorialist:Pushkar Mishra

DIFFICULTY:

Easy-Medium

PREREQUISITES:

Ad Hoc, Observation

PROBLEM:

Given are $N+1$ numbers $A_0$ to $A_N$. These numbers come in as a stream in order from $A_0$ to $A_N$. The number coming in can be placed at either ends of the sequence already present. Score of such a gameplay is calculated as per given rules. Output the sum of scores of all possible different gameplays.

EXPLANATION:

Subtask 1
Subtask 1 can be solved by directly simulating the given problem. In other words, we can directly append the number coming in at either ends and check the sum for each possible arrangement. There can at maximum be $2^N$ different sequences. Therefore, the time complexity is $\mathcal{O}(2^N)$ per test case. This is sufficient for this subtask.

Subtask 2
Let us start by thinking of simpler sequences in which observing patterns could be easier. A trick is to take something like 1, 1, 1, ...., 1, 5 as the sequence. And then the 5 can be shuffled around to different positions to observe how many times a position is taken into account.

Nevertheless, we are going to take a more mathematical approach in this editorial. Let's see what happens when $k^{th}$ number, i.e., $A[k]$ appears in the stream. It can be appended to either of the two ends of the already existing sequence. But how many already existing sequence are there? Clearly, $2^{(k-1)}$. Let us say for now that $A[k]$ is appended to the right of already existing sequence. Now, consider some $p^{th}$ number $A[p]$ coming after $A[k]$. How many sequences exist such that the $A[p]$ will be multiplied by $A[k]$? For $A[p]$ to be multiplied by $A[k]$, all numbers coming in between these two must not go to the side that $A[k]$ is on, i.e., they should be put on the left in all the $2^{(k-1)}$ sequences where $A[k]$ has been appended on the right. If this happens, then when $A[p]$ comes, it will be multiplied by $A[k]$ when placed on the right of it. The $(p+1)^{th}$ up till $N^{th}$ numbers can be arranged in any order after that. So how many sequences in total will have the product of $A[k]$ and $A[p]$? Clearly, $2^{(k-1)}*2^{(N-p)}$. Thus, total value that gets added to the answer is $(A[k]*2^{(k-1)})*(A[p]*2^{(N-p)})$.

We now have a way to calculate the required answer. Below is the pseudocode of the same.

let possible_future_prod[i] = A[i] * 2^(N-i)

let answer = 0; //accumulator variable
for i = 0 to N-1
{
    ways_to_arrange_prefix = 2^(i-1); //if i = 0, then 1

    //multipying A[i] with the number of possible prefixes
    partial_prod = (ways_to_arrange_prefix * A[i]);

    //iterating over elements coming after i
    for j = i+1 to N
    {
        total_prod = partial_prod * possible_future_prod[j];

        //adding total_prod to the accumulator variable
        ans += total_prod;
    }
}

//recall, we had only taken the case when an element is
//appended to the right.
//for taking symmetrical cases into account, multiply by 2.
return 2*ans

This algorithm runs in $\mathcal{O}(N^2)$.

Subtask 3
The algorithm stated in subtask 2 can be made $\mathcal{O}(N)$ by precalculating the suffix sum of the $possible\_future\_sequences$ array. Once we have the $suffix\_sum$ array, the inner loop given above in the pseudocode can be reduced to:

//calculating the suffix_sum array
suffix_sum[n] = possible_future_prod[n]
for i = N-1 downto 0
    suffix_sum[i] = possible_future_prod[i] + suffix_sum[i-1];

let answer = 0; //accumulator variable
for i = 0 to N-1
{
    ways_to_arrange_prefix = 2^(i-1); //if i = 0, then 1

    //multipying A[i] with the number of possible prefixes
    partial_prod = (ways_to_arrange_prefix * A[i]);

    //calculating the sum that can be achieved by
    //multiplying A[i] with numbers coming after it
    total_prod = (partial_prod * suffix_sum[i+1]);

    //adding total_prod to the accumulator variable
    ans += total_prod;
}

//for taking symmetrical cases into account, multiply by 2
return 2*ans

The editorialist's program follows the editorial. Please see for implementation details.

OPTIMAL COMPLEXITY:

$\mathcal{O}(N)$ per test case.

SAMPLE SOLUTIONS:

Author
Tester
Editorialist

what is the problem in my code ?

$
0
0

Hi I am trying to solve SUMTRIAN problem it is work good in my computer but when i put the code in the website I have the time limit problem this is my code if any one can help me ,plz? * I am sorry about my English Language

package codechef;
import java.util.Scanner;
class SUMTRIAN {
private static int Trian[][];
//private static int SumTrian[];
private static int rows;
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int case1 = input.nextInt();
    for (int s = 0;s<case1;s++){
        rows= input.nextInt();
        Trian = new int[rows*rows][rows*rows];
        //SumTrian = new int[rows];
        for(int row = 0;row <rows;row++)
            for (int col = 0;col<=row;col++)
                Trian[row][col]=input.nextInt();
        System.out.println(solve(0,0));

    }
}
public static int solve(int row,int col){
    if(row>rows-1)
        return 0;
    else{
        int t1 = solve(row+1,col);
        int t2 = solve(row+1,col+1);
        int t = Trian[row][col]+max(t1,t2);
        return t;
    }
}
public static int max(int t1,int t2){
    int max = t1;
    if(t2>max)
        max = t2;
    return max;

}
}
Viewing all 39796 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>