• Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
Friday, January 27, 2023
  • Login
Zeroplusfour
No Result
View All Result
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
  • Home
  • Top Posts
  • Code Solutions
  • How to
  • News
  • Trending
  • Anime
  • Health
  • Education
No Result
View All Result
Zeroplusfour
No Result
View All Result
Home Code Solutions Hackerrank Algorithms

Demanding Money- HackerRank Solution

Demanding Money - HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

bhautik bhalala by bhautik bhalala
May 26, 2022
Reading Time: 1 min read
0
15 Days to learn SQL Hard SQL(Advanced)-Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution alt text

Spread the love

Table of Contents

  • Demanding Money  – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
  • Solutions of Algorithms Data Structures Hard HackerRank:
    • Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
  • C++ Demanding Money HackerRank Solution
  • Java Demanding Money HackerRank Solution
  • Python 3 Demanding Money HackerRank Solution
  • Python 2 Demanding Money HackerRank Solution
  • C Demanding Money HackerRank Solution
    • Leave a comment below
      • Related posts:

Demanding Money  – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Solutions of Algorithms Data Structures Hard HackerRank:

Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts

C++ Demanding Money HackerRank Solution


Copy Code Copied Use a different Browser

#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <set>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <complex>
#include <map>
#include <queue>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<vi> vvi;
typedef vector<double> vd;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef vector<pii> vii;
typedef vector<string> vs;

vvi g;
vi deg, used, c;
int ma = -1;
ll cnt = 0;
int sum = 0, c0 = 0;

void rec(int v) {
    if (v >= g.size()) {
        if (sum > ma) {
            ma = sum;
            cnt = 0;
        }
        if (sum == ma) {
            cnt += (1LL << c0);
        }
        return;
    }
    if (!used[v]) {
        sum += c[v];
        bool alone = 1;
        for (int nv : g[v]) {
            if (!used[nv]) {
                alone = false;
            }
            ++used[nv];
        }
        if (alone && c[v] == 0) ++c0;
        rec(v + 1);
        sum -= c[v];
        if (alone && c[v] == 0) --c0;
        for (int nv : g[v]) {
            --used[nv];
        }
        if (!alone) rec(v + 1);
    } else {
        rec(v + 1);    
    }
}

int main() {
    int n, m;
    cin >> n >> m;
    c.resize(n);
    for (int i = 0; i < n; ++i) cin >> c[i];
    g.resize(n);
    deg.assign(n, 0);
    used.assign(n, 0);
    for (int i = 0; i < m; ++i) {
        int a,b;
        cin >> a >> b;
        if (a > b) swap(a, b);
        --a; --b;
        g[a].push_back(b);
        //g[b].push_back(a);
        ++deg[a]; ++deg[b];
    }
    rec(0);
    cout << ma << ' ' << cnt << endl;
    return 0;
}

Java Demanding Money HackerRank Solution


Copy Code Copied Use a different Browser

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class D2 {
	InputStream is;
	PrintWriter out;
	String INPUT = "";
	
	void solve()
	{
		int n = ni(), m = ni();
		int[] a = na(n);
		long[] g = new long[n];
		for(int i = 0;i < m;i++){
			int f = ni()-1, t = ni()-1;
			g[f] |= 1L<<t;
			g[t] |= 1L<<f;
		}
		for(int i = 0;i < n;i++){
			g[i] |= 1L<<i;
		}
		
		int h = n/2;
		int[] suml = new int[1<<h];
		boolean[] okl = new boolean[1<<h];
		okl[0] = true;
		for(int i = 1;i < 1<<h;i++){
			int j = Integer.numberOfTrailingZeros(i);
			suml[i] = suml[i^1<<j] + a[j];
			okl[i] = okl[i^1<<j] && (g[j]&(i^1<<j)) == 0;
		}
		
		int[] sumh = new int[1<<n-h];
		boolean[] okh = new boolean[1<<n-h];
		okh[0] = true;
		for(int i = 1;i < 1<<n-h;i++){
			int j = Integer.numberOfTrailingZeros(i);
			sumh[i] = sumh[i^1<<j] + a[j+h];
			okh[i] = okh[i^1<<j] && ((g[j+h]>>>h)&(i^1<<j)) == 0;
		}
		
		long[] counth = new long[1<<n-h];
		for(int i = 0;i < 1<<n-h;i++){
			if(okh[i]){
				counth[i] = 1;
			}else{
				sumh[i] = -1;
			}
		}
		
		for(int j = 0;j < n-h;j++){
			for(int i = 0;i < 1<<n-h;i++){
				if(i<<~j>=0){
					int ni = i^1<<j;
					if(sumh[i] > sumh[ni]){
						sumh[ni] = sumh[i];
						counth[ni] = counth[i];
					}else if(sumh[i] == sumh[ni]){
						counth[ni] += counth[i];
					}
				}
			}
		}
		
		long maxsum = -1;
		long count = 0;
		for(int i = 0;i < 1<<h;i++){
			if(!okl[i])continue;
			long merge = 0;
			for(int j = 0;j < h;j++){
				if(i<<~j<0){
					merge |= g[j];
				}
			}
			int rem = (int)(((1L<<n)-1^merge)>>>h);
			if(sumh[rem] != -1){
				long s = sumh[rem] + suml[i];
				if(s > maxsum){
					maxsum = s;
					count = counth[rem];
				}else if(s == maxsum){
					count += counth[rem];
				}
			}
		}
		out.println(maxsum + " " + count);
	}
	
	void run() throws Exception
	{
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);
		
		long s = System.currentTimeMillis();
		solve();
		out.flush();
		if(!INPUT.isEmpty())tr(System.currentTimeMillis()-s+"ms");
	}
	
	public static void main(String[] args) throws Exception { new D2().run(); }
	
	private byte[] inbuf = new byte[1024];
	private int lenbuf = 0, ptrbuf = 0;
	
	private int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}
	
	private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
	private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
	
	private double nd() { return Double.parseDouble(ns()); }
	private char nc() { return (char)skip(); }
	
	private String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	
	private char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}
	
	private char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}
	
	private int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}
	
	private int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}
		
		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}
	
	private static void tr(Object... o) { System.out.println(Arrays.deepToString(o)); }
}

 



Python 3 Demanding Money HackerRank Solution


Copy Code Copied Use a different Browser

def solve(C,G) :
    minLost = {}
    def getMinLost(housesToVisit) :
#        print("getMinLost %s :" % str(housesToVisit))
        if not housesToVisit :
            return 0,1
        
        key = frozenset(housesToVisit)
        if key in minLost :
            return minLost[key]
        
        a = housesToVisit.pop()
        # Do not visit house a
        lost, nb = getMinLost(housesToVisit)
        lost += C[a]
        # Visit house a
        lostHouses = set(b for b in G[a] if b in housesToVisit)
        lostMoney = sum(C[b] for b in lostHouses)
        losta, nba = getMinLost(housesToVisit - lostHouses)
        losta += lostMoney
        housesToVisit.add(a)
        
        if losta < lost :
            lost, nb = losta, nba
        elif losta == lost :
            nb += nba
        
        minLost[key] = (lost,nb)
        return minLost[key]
    
    amount, number = getMinLost(set(range(len(C))))
    return sum(C)-amount, number
    
    
N,M = map(int,input().split())
C = tuple(map(int,input().split()))
G = {a : set() for a in range(len(C))}
for _ in range(M) :
    a,b = map(int,input().split())
    G[a-1].add(b-1)
    G[b-1].add(a-1)
print(" ".join(map(str,solve(C,G))))



Python 2 Demanding Money HackerRank Solution


Copy Code Copied Use a different Browser

# Enter your code here. Read input from STDIN. Print output to STDOUT

import sys
input=sys.stdin.readline

n,m=map(int,input().split())

c=list(map(int,input().split()))

g=[[] for _ in range(n)]
for _ in range(m):
    u,v=map(int,input().split())
    g[u-1].append(v-1)
    g[v-1].append(u-1)

# visit each connected component
a1=0
a2=1
vis=[0]*n
col=[0]*n   # temp colouring, 0 = not pick, 1 = pick
l1=[]
l2=[]

def getinfo(idx):
    # base case
    if idx==len(l1):
        # count
        out=0
        for i in l1:
            if col[i]:
                out+=c[i]
        return (out,1)
    # general case
    for i in g[l1[idx]]:
        if col[i]:
            # cannot rob
            return getinfo(idx+1)
    # choice of robbing
    p1,p2=getinfo(idx+1)
    col[l1[idx]]=1
    q1,q2=getinfo(idx+1)
    col[l1[idx]]=0
    if p1==q1:
        return (p1,p2+q2)
    return max((p1,p2),(q1,q2))

for i in range(n):
    if not vis[i]:
        # dfs that is horrible to code
        l1=[i]
        l2=[i]
        vis[i]=1
        while l2:
            u=l2.pop(-1)
            for v in g[u]:
                if not vis[v]:
                    l1.append(v)
                    l2.append(v)
                    vis[v]=1
        # get money info
        b1,b2=getinfo(0)
        a1+=b1
        a2*=b2

# print
print("%s %s"%(a1,a2))



C Demanding Money HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>
#include <stdlib.h>
#define HASH_SIZE 123455
typedef struct _node{
  long long x;
  int aa;
  long long bb;
  struct _node *next;
} node;
void insert_edge(int x,int y,int w);
void insert(long long x,int aa,long long bb);
int search(long long x,int *aa,long long *bb);
void solve(long long x,int *aa,long long *bb);
int a[34],N;
long long link[34]={0};
node *hash[HASH_SIZE]={0};

int main(){
  int M,x,y,i;
  long long ans;
  scanf("%d%d",&N,&M);
  for(i=0;i<N;i++)
    scanf("%d",a+i);
  for(i=0;i<M;i++){
    scanf("%d%d",&x,&y);
    insert_edge(x-1,y-1,1);
  }
  solve((1LL<<N)-1,&x,&ans);
  printf("%d %lld",x,ans);
  return 0;
}
void insert_edge(int x,int y,int w){
  link[x]|=(1LL<<y);
  link[y]|=(1LL<<x);
  return;
}
void insert(long long x,int aa,long long bb){
  int bucket=x%HASH_SIZE;
  node *t=hash[bucket];
  t=(node*)malloc(sizeof(node));
  t->x=x;
  t->aa=aa;
  t->bb=bb;
  t->next=hash[bucket];
  hash[bucket]=t;
  return;
}
int search(long long x,int *aa,long long *bb){
  int bucket=x%HASH_SIZE;
  node *t=hash[bucket];
  while(t){
    if(t->x==x){
      *aa=t->aa;
      *bb=t->bb;
      return 1;
    }
    t=t->next;
  }
  return 0;
}
void solve(long long x,int *aa,long long *bb){
  int aa1,aa2,i;
  long long bb1,bb2;
  if(!x){
    *aa=0;
    *bb=1;
    return;
  }
  if(search(x,aa,bb))
    return;
  for(i=0;i<N;i++)
    if((1LL<<i)&x)
      break;
  solve(x&(~(1LL<<i)),&aa1,&bb1);
  solve(x&(~link[i])&(~(1LL<<i)),&aa2,&bb2);
  aa2+=a[i];
  if(aa1==aa2)
    bb1+=bb2;
  else if(aa2>aa1){
    aa1=aa2;
    bb1=bb2;
  }
  *aa=aa1;
  *bb=bb1;
  insert(x,aa1,bb1);
  return;
}

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionTask Scheduling – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMerge two sorted linked lists – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionRecursive Digit Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLego Blocks – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDijkstra: Shortest Reach 2 – HackerRank Solution
Tags: Cc++14Demanding Moneyfull solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3
ShareTweetPin
bhautik bhalala

bhautik bhalala

Related Posts

Leetcode All Problems Solutions
Code Solutions

Exclusive Time of Functions – LeetCode Solution

by admin
October 5, 2022
0
29

Exclusive Time of Functions - LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions...

Read more
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
32
Leetcode All Problems Solutions

Course Schedule III – LeetCode Solution

October 5, 2022
25
Leetcode All Problems Solutions

Maximum Product of Three Numbers – LeetCode Solution

September 11, 2022
52
Leetcode All Problems Solutions

Task Scheduler – LeetCode Solution

September 11, 2022
119
Leetcode All Problems Solutions

Valid Triangle Number – LeetCode Solution

September 11, 2022
28
Next Post
15 Days to learn SQL Hard SQL(Advanced)-Solution

The Value of Friendship - HackerRank Solution

15 Days to learn SQL Hard SQL(Advanced)-Solution

Coprime Paths - HackerRank Solution

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

You may also like

15 Days to learn SQL Hard SQL(Advanced)-SolutionTask Scheduling – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionMerge two sorted linked lists – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionRecursive Digit Sum – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionLego Blocks – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionDijkstra: Shortest Reach 2 – HackerRank Solution

Categories

  • Algorithms
  • Anime
  • Biography
  • Business
  • Code Solutions
  • Cosmos
  • Countdowns
  • Culture
  • Economy
  • Education
  • Entertainment
  • Finance
  • Games
  • Hackerrank
  • Health
  • How to
  • Investment
  • LeetCode
  • Lifestyle
  • LINUX SHELL
  • Manga
  • News
  • Opinion
  • Politics
  • Sports
  • SQL
  • Tech
  • Travel
  • Uncategorized
  • Updates
  • World
  • DMCA
  • Home
  • My account
  • Privacy Policy
  • Top Posts

Recent Blogs

Leetcode All Problems Solutions

Exclusive Time of Functions – LeetCode Solution

October 5, 2022
Leetcode All Problems Solutions

Smallest Range Covering Elements from K Lists – LeetCode Solution

October 5, 2022
Biography

Taapsee Pannu Net Worth, Age, Height , Achivements and more

September 8, 2022
0
Kaido (Uo Uo no Mi, Model: Seiryu) One Piece
Anime

One Piece Chapter 1049 Release Date Countdown

May 11, 2022
131
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Placements MediumSQL (Intermediate) – SQL – HackerRank Solution

May 30, 2022
5
One Piece Chapter 1059 Raw Scan English Manga Spoilers
Anime

One Piece Chapter 1059 Raw Scan English Manga Spoilers: Sabo’s Plan

September 7, 2022
191

© 2022 ZeroPlusFour - Latest News & Blog.

No Result
View All Result
  • Home
  • Category
    • Business
    • Culture
    • Economy
    • Lifestyle
    • Health
    • Travel
    • Opinion
    • Politics
    • Tech
  • Landing Page
  • Support Forum
  • Contact Us

© 2022 ZeroPlusFour - Latest News & Blog.

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent.
Cookie SettingsAccept All
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.
Others
Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.
SAVE & ACCEPT
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?