Thursday 21 December 2017

Codeforces Problem 102B Solution in (C++)


Welcome:

The question to the problem can be found here:


Explanation:
1.Enter the integer as an character.
2.This will separate the biggest integer into smaller pieces.
3.Convert the pieces into integer and then add using a variable and store in the array s.
4.Convert the piece into character array
5.Continue until only 1 character is present.
6.Happy Coding.

Code:
#include<bits/stdc++.h>
using namespace std;
char s[100000];
int main(){
int cnt=0;
cin>>s;

while(s[1]){
cnt++;
int res =0;
for(int i=0;s[i];i++)
    res+= s[i] - '0';
    sprintf(s,"%d",res);
}

cout<<cnt;

return 0;}

Thursday 7 December 2017

Hackerrank Problem Breadth First Search: Shortest Reach C++

Welcome:

The question to the problem can be found here:

Explanation:
1.Take input as explained in the question.
2.Conduct a breadth first search taking s(input) as the starting index and n(last node).
3.Print all the distances available from s. If level is  zero print -1 that means there is no path from the start symbol to this node.

Happy Coding :)

Code:

#include<bits/stdc++.h>
using namespace std;

vector<int> adj[10000]; //adj[a].push_back(b); for add an edge from a to b
int visited[10000]={0}; //O if not visited, 1 if visited
int level[10000];

void addEdge(int v, int w)
{
    adj[v].push_back(w); // Add w to v’s list.
 adj[w].push_back(v);
}

void bfs(int s, int n)
{
    for(int i=0; i<10000;i++){
        visited[i] = 0;
    level[i]=0;
    }
    queue<int>Q;
    Q.push(s);
    visited[s] = 1;
    level[s] = 0;

    while(!Q.empty())
    {
        int u = Q.front();

        for(int i=0; i<adj[u].size(); i++){
            if(visited[adj[u][i]]==0){
                int v = adj[u][i];
                level[v] = level[u]+6;
                visited[v] = 1;
                Q.push(v);
            }
        }
        Q.pop();
    }

  for(int i=1;i<=n;i++)
    {
        if(i!=s)
        {
            if(level[i]==0)
            cout<<"-1 ";
            else
            cout<<level[i]<<" ";
        }
    }
    cout<<endl;
}

int main()
{
    int q;
   cin>>q;
  while(q-->0){

    int n,m;
   cin>>n>>m;
    for(int i=0;i<n+3;i++)
         adj[i].clear();
   for(int i=0;i<m;i++){
        int u,v;
   cin>>u>>v;
   addEdge(u,v);
   }
   int s;
   cin>>s;
bfs(s,n);
}
}

Spoj Problem ACMCEG2C - Pick the candies (C++)

  The problem link may be found here.       Explanation: Use Deque to keep track of elements of the variety of candies. If i is gre...