• 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

Tripartite Matching – HackerRank Solution

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

bhautik bhalala by bhautik bhalala
May 27, 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

  • Tripartite Matching – 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++ Tripartite Matching HackerRank Solution
  • Java Tripartite Matching HackerRank Solution
  • Python 3 Tripartite Matching HackerRank Solution
  • Python 2 Tripartite Matching HackerRank Solution
  • C Tripartite Matching HackerRank Solution
    • Leave a comment below
      • Related posts:

Tripartite Matching – 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++ Tripartite Matching HackerRank Solution


Copy Code Copied Use a different Browser

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<cstdio>
#include<numeric>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<set>
#include<map>
#include<unordered_map>
#include<unordered_set>
#include<list>
#include<cmath>
#include<bitset>
#include<cassert>
#include<queue>
#include<stack>
#include<deque>
#include<cassert>
using namespace std;
typedef long long ll;
typedef long double ld;
const int MAXN = 100 * 1000 + 1;
typedef bitset<MAXN> bs;
int deg1[MAXN], deg2[MAXN];
vector<int>g1[MAXN], g2[MAXN];
unordered_set<long long>have1, have2;

int calc(int u, int v) // u - first, v - third
{
	int res = 0;
	if (deg1[u] < deg2[v])
	{
		for (int i = 0; i < (int)g1[u].size(); i++)
		{
			int to = g1[u][i];
			if (to == v) continue;
			res += have2.count(1LL * MAXN * v + to);
		}
	}
	else
	{
		for (int i = 0; i < (int)g2[v].size(); i++)
		{
			int to = g2[v][i];
			if (to == v) continue;
			res += have1.count(1LL * MAXN * u + to);
		}
	}
	return res;
}
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n;
	scanf("%d", &n);
	int m;
	scanf("%d", &m);
	have1.rehash(10 * 1000 * 1000);
	have2.rehash(10 * 1000 * 1000);
	for (int i = 1; i <= m; i++)
	{
		int u, v;
		scanf("%d %d", &u, &v);
		g1[u].push_back(v);
		have1.insert(1LL * MAXN * u + v);
		have1.insert(1LL * MAXN * v + u);
		g1[v].push_back(u);
		deg1[u]++;
		deg1[v]++;
	}
	vector<pair<int, int> >mid;
	scanf("%d", &m);
	for (int i = 1; i <= m; i++)
	{
		int u, v;
		scanf("%d %d", &u, &v);
		mid.push_back(make_pair(u, v));
	}
	scanf("%d", &m);
	for (int i = 1; i <= m; i++)
	{
		int u, v;
		scanf("%d %d", &u, &v);
		deg2[u]++;
		deg2[v]++;
		g2[u].push_back(v);
		g2[v].push_back(u);
		have2.insert(1LL * MAXN * u + v);
		have2.insert(1LL * MAXN * v + u);
	}
	ll ans = 0;
	for (int i = 0; i < (int)mid.size(); i++)
	{
		int u = mid[i].first, v = mid[i].second;
		ans += calc(u, v);
		ans += calc(v, u);
	}
	printf("%lld\n", ans);
}

Java Tripartite Matching 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 D {
	InputStream is;
	PrintWriter out;
	String INPUT = "";
	
	int[][] read(int n)
	{
		int m = ni();
		int[] from = new int[m];
		int[] to = new int[m];
		for(int i = 0;i < m;i++){
			from[i] = ni()-1;
			to[i] = ni()-1;
		}
		return packU(n, from, to);
	}
	
	void solve()
	{
		int n = ni();
		int[][] ga = read(n);
		int[][] gb = read(n);
		int[][] gc = read(n);
		
		int S = (int)Math.sqrt(100000);
		long[][] gbb = new long[n][];
		long[][] gbc = new long[n][];
		for(int i = 0;i < n;i++){
			if(gb[i].length >= S){
				gbb[i] = new long[(n>>>6)+1];
				for(int e : gb[i]){
					gbb[i][e>>>6] |= 1L<<e;
				}
			}
			if(gc[i].length >= S){
				gbc[i] = new long[(n>>>6)+1];
				for(int e : gc[i]){
					gbc[i][e>>>6] |= 1L<<e;
				}
			}
			Arrays.sort(gb[i]);
			Arrays.sort(gc[i]);
		}
		
		int na = ga.length;
		long ret = 0;
		for(int a = 0;a < na;a++){
			for(int b : ga[a]){
				if(gbb[b] != null){
					if(gbc[a] != null){
						for(int i = 0;i < (n>>>6)+1;i++){
							ret += Long.bitCount(gbb[b][i]&gbc[a][i]);
						}
					}else{
						for(int e : gc[a]){
							if(gbb[b][e>>>6]<<~e<0)ret++;
						}
					}
				}else{
					if(gbc[a] != null){
						for(int e : gb[b]){
							if(gbc[a][e>>>6]<<~e<0)ret++;
						}
					}else{
						for(int i = 0, j = 0;i < gb[b].length && j < gc[a].length;){
							if(gb[b][i] == gc[a][j]){
								ret++; i++; j++;
							}else if(gb[b][i] < gc[a][j]){
								i++;
							}else{
								j++;
							}
						}
					}
				}
			}
		}
		out.println(ret);
	}
	
	static int[][] packU(int n, int[] from, int[] to) {
		int[][] g = new int[n][];
		int[] p = new int[n];
		for (int f : from)
			p[f]++;
		for (int t : to)
			p[t]++;
		for (int i = 0; i < n; i++)
			g[i] = new int[p[i]];
		for (int i = 0; i < from.length; i++) {
			g[from[i]][--p[from[i]]] = to[i];
			g[to[i]][--p[to[i]]] = from[i];
		}
		return g;
	}
	
	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 D().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 Tripartite Matching HackerRank Solution


Copy Code Copied Use a different Browser

vertices = int(input())
graph = [[], [], [], []]
count = 0
G1 = 1
G2 = 2
G3 = 3

for i in range(1, 4):
    for j in range(0, vertices + 1):
        graph[i].append(None)

for i in range(1, 4):
    edges = int(input())
    for j in range(0, edges):
        edge = list(map(int, input().split(" ")))
        if graph[i][edge[0]] is None:
            graph[i][edge[0]] = set()
        graph[i][edge[0]].add(edge[1])
        if graph[i][edge[1]] is None:
            graph[i][edge[1]] = set()
        graph[i][edge[1]].add(edge[0])

for vertex in range(1, vertices + 1):
    verticesToG1 = graph[G1][vertex]
    if verticesToG1 is not None:
        verticesFromG2 = graph[G2][vertex]
        if verticesFromG2 is not None:
            for toVertex in verticesFromG2:
                verticesFromG3 = graph[G3][toVertex]
                if verticesFromG3 is not None:
                    count = count + len(verticesToG1.intersection(verticesFromG3))
        
print(count)



Python 2 Tripartite Matching HackerRank Solution


Copy Code Copied Use a different Browser

#!/usr/bin/env python

import sys

def main():
    N = int(sys.stdin.readline())
    M = []
    G = []
    for i in xrange(3):
        M.append(int(sys.stdin.readline()))
        G.append([set() for _ in xrange(N)])
        for _ in xrange(M[i]):
            u,v = map(int, sys.stdin.readline().split())
            u,v = u-1,v-1
            G[i][u].add(v)
            G[i][v].add(u)
    cpt = 0
    for a in xrange(N):
        for b in G[0][a]:
            for c in G[1][b]:
                if a in G[2][c]:
                    #print a,b,c
                    cpt += 1
    print cpt

main()



C Tripartite Matching HackerRank Solution


Copy Code Copied Use a different Browser

#include <stdio.h>
#include <stdlib.h>
#define HASH_SIZE 1234555
typedef struct _node{
  int x;
  int y;
  struct _node *next;
} node;
typedef struct _lnode{
  int x;
  struct _lnode *next;
} lnode;
void insert_edge(int x,int y,int *len,lnode **table,node **hash);
void insert(node **hash,int x,int y);
int search(node **hash,int x,int y);
int len1[100000],len2[100000],*t1[100000],*t2[100000];
node *hash1[HASH_SIZE],*hash2[HASH_SIZE];
lnode *table1[100000],*table2[100000];

int main(){
  int n,m,x,y,i,j;
  long long ans=0;
  lnode *p;
  scanf("%d",&n);
  scanf("%d",&m);
  for(i=0;i<m;i++){
    scanf("%d%d",&x,&y);
    insert_edge(x-1,y-1,len1,table1,hash1);
  }
  scanf("%d",&m);
  for(i=0;i<m;i++){
    scanf("%d%d",&x,&y);
    insert_edge(x-1,y-1,len2,table2,hash2);
  }
  for(i=0;i<n;i++)
    if(len1[i]){
      t1[i]=(int*)malloc(len1[i]*sizeof(int));
      for(p=table1[i],j=0;p;p=p->next,j++)
        t1[i][j]=p->x;
    }
  for(i=0;i<n;i++)
    if(len2[i]){
      t2[i]=(int*)malloc(len2[i]*sizeof(int));
      for(p=table2[i],j=0;p;p=p->next,j++)
        t2[i][j]=p->x;
    }
  scanf("%d",&m);
  for(i=0;i<m;i++){
    scanf("%d%d",&x,&y);
    x--;
    y--;
    if(len1[x]<len2[y])
      for(j=0;j<len1[x];j++)
        ans+=search(hash2,t1[x][j],y);
    else
      for(j=0;j<len2[y];j++)
        ans+=search(hash1,t2[y][j],x);
    if(len1[y]<len2[x])
      for(j=0;j<len1[y];j++)
        ans+=search(hash2,t1[y][j],x);
    else
      for(j=0;j<len2[x];j++)
        ans+=search(hash1,t2[x][j],y);
  }
  printf("%lld",ans);
  return 0;
}
void insert_edge(int x,int y,int *len,lnode **table,node **hash){
  lnode *t=malloc(sizeof(lnode));
  t->x=y;
  t->next=table[x];
  table[x]=t;
  len[x]++;
  t=malloc(sizeof(lnode));
  t->x=x;
  t->next=table[y];
  table[y]=t;
  len[y]++;
  insert(hash,x,y);
  insert(hash,y,x);
  return;
}
void insert(node **hash,int x,int y){
  int bucket=(x*100000LL+y)%HASH_SIZE;
  node *t=hash[bucket];
  t=(node*)malloc(sizeof(node));
  t->x=x;
  t->y=y;
  t->next=hash[bucket];
  hash[bucket]=t;
  return;
}
int search(node **hash,int x,int y){
  int bucket=(x*100000LL+y)%HASH_SIZE;
  node *t=hash[bucket];
  while(t){
    if(t->x==x && t->y==y)
      return 1;
    t=t->next;
  }
  return 0;
}

 

Leave a comment below

 

Related posts:

15 Days to learn SQL Hard SQL(Advanced)-SolutionMaking Candies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – 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 15 Days to learn SQL Hard SQL(Advanced)-SolutionMatrix – HackerRank Solution
Tags: Cc++14full solutionGoHackerRank Solutionjavajava 15java 7java 8java8javascriptpypy 3Python 2python 3Tripartite Matching
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

Jogging Cats - HackerRank Solution

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

Quadrant Queries - 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)-SolutionMaking Candies – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionSimilar Pair – HackerRank Solution 15 Days to learn SQL Hard SQL(Advanced)-SolutionCounting Sort 1 – 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 15 Days to learn SQL Hard SQL(Advanced)-SolutionMatrix – 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
15 Days to learn SQL Hard SQL(Advanced)-Solution
Code Solutions

Weather Observation Station 8 EasySQL (Basic) – SQL – HackerRank Solution

May 30, 2022
1
15 Days to learn SQL Hard SQL(Advanced)-Solution
Algorithms

Matrix Land – HackerRank Solution

May 31, 2022
27
Leetcode All Problems Solutions
Code Solutions

House Robber II – LeetCode Solution

September 5, 2022
24
Shark Tank
Business

Umaro Net Worth 2022 – What Happened After Shark Tank? Everything You need to know.

September 4, 2022
0

© 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?