LeetCode:Happy Numbers

No comments

Problem :

https://leetcode.com/problems/happy-number/
#include<bits/stdc++.h>
using namespace std;
class Solution 
{
 
	public:
    	bool isHappy(int n) 
	{
		map<int,int>a;
		while(a[n]!=1)
		{
			a[n]=1;
        		int sum=0,res=0;
			while(n)
			{
				res=n%10;
				sum+=(res*res);
				n/=10;
			}
			if(sum==1)
			return true;
			else
			{
				n=sum;
			}
		}
		return false;
    	}
};
int main()
{
	Solution s;	
	cout<<s.isHappy(19)<<endl;
	cout<<s.isHappy(301)<<endl;
}

No comments :

SPOJ:ABCDEF

No comments

Problem :

http://www.spoj.com/problems/ABCDEF/

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll long long
#define rl(x) scanf("%lld",&x)
ll  a1[105];
ll  arr1[2000000];
int main()
{
 ll n,temp1=0,v,ans=0;
 rl(n);
 for(int i=0;i<n;i++)
 rl(a1[i]);
 for(int a=0;a<n;a++)
     if(a1[a])
            for(int b=0;b<n;b++)
        for(int c=0;c<n;c++)
           arr1[temp1++]=(a1[a]*(a1[b]+a1[c]));
        sort(arr1,arr1+temp1);
 for(int d=0;d<n;d++)
           for(int e=0;e<n;e++)
       for(int f=0;f<n;f++)
              {
    v=a1[d]*a1[e]+a1[f];
    ans+=(upper_bound(arr1,arr1+temp1,v))-(lower_bound(arr1,arr1+temp1,v));
              }
 cout<<ans<<endl;
 
} 
 

No comments :

SPOJ:ADDREV

No comments

Problem :

http://www.spoj.com/problems/ADDREV/
#include<iostream>
using namespace std;
long long phi(long long n) 
{ 
 long  long result = n; 
        for(long  long i=2;i*i <= n;i++) 
        { 
  if (n%i==0) 
  result-=result/i; 
         while (n%i==0) 
  n/=i; 
        } 
        if (n>1) 
 result-=result/n; 
        return result; 
} 
int main()
{
 long long t,n;
 cin>>t; 
 while(t--)
 {
  cin>>n;
  cout<<phi(n)<<endl;
 }
} 

No comments :

SPOJ:ETF

No comments

Problem :

http://www.spoj.com/problems/ETF/
#include<iostream>
using namespace std;
long long phi(long long n) 
{ 
	long  long result = n; 
        for(long  long i=2;i*i <= n;i++) 
        { 
		if (n%i==0) 
		result-=result/i; 
        	while (n%i==0) 
		n/=i; 
        } 
        if (n>1) 
	result-=result/n; 
        return result; 
} 
int main()
{
	long long t,n;
	cin>>t;	
	while(t--)
	{
		cin>>n;
		cout<<phi(n)<<endl;
	}
} 

No comments :

SPOJ:NAKANJ(Minimum Knight Moves !!!)

No comments

Problem:

http://www.spoj.com/problems/NAKANJ/

The problem is a simple application of BFS,even though the problem can be solved in different methods BFS is easy to implement>
The algorithm is to keep track of all the neighbouring vertices in a queue by checking the boundary cases and incrementing the corresponding distace.Whenever we find the destination point we return the distace at that point

Below code is the c++ implementation for the above problem

 
    #include<set>
    #include<map>
    #include<list>
    #include<stack>
    #include<queue>
    #include<cmath>
    #include<vector>
    #include<cstdio>
    #include<cctype>
    #include<deque>
    #include<bitset>
    #include<utility>
    #include<climits>
    #include<cstdlib>
    #include<cstring>
    #include<iomanip>
    #include<iostream>
    #include<algorithm>
    using namespace std;
    //#include<sai> tHe lAzY PrOgRmMeR :)
    #define rl(T) scanf("%lld",&T)
    #define ri(T) scanf("%d",&T)
    #define rs(T) scanf("%s",T)
    #define rc(T) scanf("%c",&T)
    #define loop(i,a,n) for(long long i=a;i<n;i++)
    #define loopn(i,a,n) for(long long i=1;i<=n;i++)
    #define ll long long
    int x[10]={0,-1,-1,-2,-2,2,2,1,1};
    int y[10]={0,-2,2,-1,1,-1,1,-2,2};
    using namespace std;
    int bfs(int a1,int b1,int a2,int b2)
    {
         int moves[9][9],vis[9][9],m,n;
         pair<int,int>p1;
         queue< pair<int,int> >q;
         p1.first=a1;
         p1.second=b1;
         q.push(p1);
         memset(moves,0,sizeof moves);
         memset(vis,0,sizeof vis);
         vis[a1][b1]=0;
         while(!q.empty())
         {
             p1=q.front();
             q.pop();
             if(p1.first==a2 && p1.second==b2)
             return moves[a2][b2];
             for(int i=1;i<=8;i++)
             {
                 m=p1.first+x[i],n=p1.second+y[i];
                 if(m>8 || m<1 || n>8 || n<1)
                 continue;
                 else
                 {
                     vis[m][n]=1;
                     moves[m][n]=moves[p1.first][p1.second]+1;
                     q.push(make_pair(m,n));
                 }
             }
         }
    }
    int main()
    {
       char a1,a2;
       ll b1,b2,t;
       rl(t);
       while(t--)
       {
          cin>>a1>>b1>>a2>>b2;
          cout<<bfs(a1-'a'+1,b1,a2-'a'+1,b2)<<endl;
       } 
    } 

No comments :

LeetCode :Palindrome Number

No comments
Problem:

Link

#include<bits/stdc++.h>
using namespace std;
class Solution 
{
    public:
    bool isPalindrome(int x) 
    {
        if(x<0)
 return false;
 stringstream ss;
 ss<<x;
 string s1="",s,temp;
 s=ss.str();
 for(int i=0;i<s.length();i++)
 {
  if(s[i]!=' ')
  s1+=s[i];
 }
 temp=s1;
 reverse(s1.begin(),s1.end());
 return s1==temp?true:false;
    }
};
int main()
{
 Solution s;
 cout<<s.isPalindrome(131)<<endl;
 cout<<s.isPalindrome(-456)<<endl;
}

No comments :

LeetCode :Excel Sheet Column Number

No comments
Problem:

Link

#include<bits/stdc++.h>
using namespace std;
class Solution 
{
	public:
  	int titleToNumber(string s) 
	{
        	int n=s.length(),ans=0;
		for(int i=0;i<n;i++)
		{
			ans+=(pow(26,n-i-1))*(s[i]-'A'+1);
 
		}
		return ans;
    	}
};

No comments :

LeetCode :Factorial Trailing Zeroes

No comments
Problem:
https://leetcode.com/problems/factorial-trailing-zeroes/

Reference : http://www.mytechinterviews.com/how-many-trailing-zeros-in-100-factorial

#include<iostream>
using namespace std;
class Solution 
{
public:
      int trailingZeroes(int n) {
        int count = 0;
        long k = 5;
        while(n >= k)
        {
            count+=n/k;
            k*=5;
        }
        return count;
    }
};
int main()
{
	Solution s;
	cout<<s.trailingZeroes(100)<<endl;
}

No comments :

LeetCode :Reverse Integer

1 comment
Problem:
https://leetcode.com/problems/reverse-integer/
#include<bits/stdc++.h>
using namespace std;
class Solution 
{
 public:
     int reverse(int x) 
 { 
  int res=0,ans=0,f=0;
  while(x)
  {
   if(ans>(INT_MAX/10) || ans<(INT_MIN/10))
   return 0;
   ans=ans*10+x%10;
   x/=10;
 
  }
 
  return ans;
 
   }
};

1 comment :

LeetCode :Spiral Matrix

No comments
Problem:
https://leetcode.com/problems/spiral-matrix/
#include<bits/stdc++.h>
using namespace std;
class Solution 
{
	public:
    	vector<int> spiralOrder(vector<vector<int> > &matrix) 
	{
		vector<int>v;
		if(matrix.size()==0)
		return v;
 
        	int t=0,b=matrix.size()-1,l=0,r=matrix[0].size()-1;
		while(1)
		{
			for(int i=t;i<=r;i++)
			v.push_back(matrix[t][i]);t++;
			if(l>r || t>b) break;
			for(int i=t;i<=b;i++)
			v.push_back(matrix[i][r]);r--;
			if(l>r || t>b) break;
			for(int i=r;i>=l;i--)
			v.push_back(matrix[b][i]);b--;
			if(l>r || t>b) break;
			for(int i=b;i>=t;i--)
			v.push_back(matrix[i][l]);l++;
			if(l>r || t>b) break;
 
 
 
		}
	return v;
    	}
};

No comments :

LeetCode:ReverseBits

No comments
Problem:
https://leetcode.com/problems/reverse-bits/

My brute force solutions get accepted,the algorithm is to push all the remainders into a stack and then multiplying each bit with corresponding power of 2

#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
 int reverseBits(int n) 
 {
         int x=1,i=0;
  long long res=0;
  stack<int>st;
  while(x<=32)
  {
   st.push(abs(n%2));
   n>>=1;
   x++;
  }
  res=0;
  while(!st.empty())
  { 
   res+=(st.top()*(pow(2,i)));
   i++;
   st.pop();
  }
  return res;
   }
};

Reference :

Here

Method 2

#include<bits/stdc++.h>
#define INT_SIZE 32
using namespace std;
class Solution 
{
 public:
 int reverseBits(unsigned int num)
 {
  int i=INT_SIZE-1;
  unsigned int rev_num=0;
  while(i>=0 && num)
  {
   if(num & 1)
   rev_num |= (1<<i);
   num>>=1;
   i--;
  }
 return rev_num;
 }
};
int main()
{
 Solution s;
 cout<<s.reverseBits(8)<<endl;
}

No comments :

MST: Kruskal's Algorithm

No comments

Kruskal's algorithm is a greedy algorithm in graph theory that finds a minimum spanning tree for a connected weighted graph.
It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized.
This algorithm needs to sort edges in non-decreasing order and uses a disjoint-set data structure to keep track which vertex is in which component.

Algorithm:Kruskal

MST-KRUSKAL(G,w) 1 A = φ 2. for each vertex 2 ∈ G:V 3. Make_set{} 4. Sort the edges in non-decreasing order by weight 5. for each edge(u,v) ∈ G,E is taken from non-decreasing order by weight 6. if(find_set(u)!=find_set(v) 7. A=A U {(u,v)} 8. Union(u,v) 9. return A

Here is the C++ implementation of Kruskal algorithm
#include<bits/stdc++.h>
using namespace std;
#define MAX 100
#define edge pair< int,int >
vector< pair<int,edge> >G,MST;
int parent[MAX];
void reset(int n)
{
 G.clear();
 MST.clear();
 for(int i=0;i<=n;i++)
 parent[i]=i;
 
}
int find(int x)
{
 if(x!=parent[x])
 parent[x]=find(parent[x]);
 return parent[x];
}
int main()
{
 int n,e,u,v,w,pu,pv,total=0;
 cin>>n>>e;
 reset(n);
 for(int i=0;i<e;i++)
 {
  cin>>u>>v>>w;
  G.push_back(pair<int,edge >(w,make_pair(u,v)));// w(u,v) format
 }
 sort(G.begin(),G.end());    //sort will be done in increasing order of weight
 for(int i=0;i<e;i++)
 {
  pu=find(G[i].second.first); 
  pv=find(G[i].second.second);
  if((pu)!=(pv))
  {
   MST.push_back(G[i]);
   total+=G[i].first;
   parent[pu]=parent[pv];
  }
 }
 for(int i=0;i<MST.size();i++)
 {
  cout<<"("<<MST[i].second.first<<" "<<MST[i].second.second<<" ) :"<<MST[i].first<<endl;
 }
 cout<<"Mimimum cost for spanning tree is :"<<total<<endl;
}

No comments :

LeetCode: Valid Palindrome

No comments
Problem:
https://leetcode.com/problems/valid-palindrome/
class Solution {
public:
    bool isPalindrome(string s) {
        int n=s.length(),f=1;
 string temp="";
 for(int i=0;i<n;i++) 
 {
  if(isalpha(s[i])||isdigit(s[i]))
  temp+=tolower(s[i]);
 }
 int len=temp.length();
 for(int i=0;i<len/2;i++) 
 {
  if(temp[i]!=temp[len-i-1])
  {
   return false;
  }
 }
 return true;
    }
};

No comments :

SPOJ: LASTDIG

No comments
Problem:
Just find the power of Last disit using Logarithmic exponentiation
Here is the C++ implementation
#include<stdio.h>
long long modexpo(long long a,long long b,long long n)
{
    long long d=1;
    while(b)
    {
        if(b%2)
            d=(d*a)%n;
        b>>=1;
        a=(a*a)%n;
    }
    return d;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        long long a,b;
        scanf("%lld%lld",&a,&b);
        printf("%lld\n",modexpo(a,b,10));
    }
    return 0;
}

No comments :

SPOJ: STPAR

No comments
Problem:
http://www.spoj.com/problems/FINDSR/
The problem is about re-ordering the given trucks in an increasing order by using a temporary street.We can solve it by using stack
Here is the C++ implementation
#include<cstdio>
#include<vector>
#include<stack>
#include<iostream>
using namespace std;
int main()
{
    long long n;
     cin>>n;
     while(n)
    {
        long long ans=1;
 
        long long a[n+10];
        for(long long i=1;i<=n;i++)
            cin>>a[i];
        stack<long long>st;
        long long strt=1;
        for(long long i=1;i<=n;i++)
        {
            if(a[i]==strt)
                strt++;
            else
            {
                if(st.empty())
                {
                      st.push(a[i]);
 
                }
 
                else if(!st.empty() && st.top()<a[i])
                {
 
                    ans=0;
                    break;
                }
                else
                    st.push(a[i]);
            }
 
            while(!st.empty() && st.top()==strt)
            {
                st.pop();
                strt++;
            }
        }
        if(!ans)
            printf("no\n");
        else if(strt-1==n && st.empty())
            printf("yes\n");
            cin>>n;
    }
}

No comments :