热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

数组中具有相同“与”、“或”和“异或”值的子集数量

数组中具有相同“与”、“或”和“异或”值的子集数量原文:http

数组中具有相同“与”、“或”和“异或”值的子集数量

原文:https://www . geesforgeks . org/数组中值相同或异或的子集数/

给定一个由非负整数组成的大小为 N 的数组 arr[] ,任务是找到数组中非空子集的数量,使得子序列的位“与”、位“或”和位“异或”值彼此相等。

注意:既然答案可以大,那就用 1000000007 来 mod 吧。

示例:

输入: arr[] = [1,3,2,1,2,1]
输出: 7
解释:
按位异或、按位或、按位与的子序列之一为{1,1,1}。

输入: arr = [2,3,4,5]
输出: 4

朴素方法这个问题的朴素方法是以迭代的方式遍历数组的所有子集,对于每个子集找到按位 and、or 和 XOR 值,并检查它们是否相等。最后,返回这样相等子集的计数。

下面是上述方法的实现:

C++

// C++ implementation to find the number
// of subsets with equal bitwise AND,
// OR and XOR values
#include
using namespace std;
const int mod = 1000000007;
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
int countSubsets(int a[], int n)
{
    int answer = 0;
    // Traverse through all the subsets
    for (int i = 0; i <(1 <        int bitwiseAND = -1;
        int bitwiseOR = 0;
        int bitwiseXOR = 0;
        // Finding the subsets with the bits
        // of 'i' which are set
        for (int j = 0; j             // Computing the bitwise AND
            if (i & (1 <                if (bitwiseAND == -1)
                    bitwiseAND = a[j];
                else
                    bitwiseAND &= a[j];
                // Computing the bitwise OR
                bitwiseOR |= a[j];
                // Computing the bitwise XOR
                bitwiseXOR ^= a[j];
            }
        }
        // Comparing all the three values
        if (bitwiseAND == bitwiseOR
            && bitwiseOR == bitwiseXOR)
            answer = (answer + 1) % mod;
    }
    return answer;
}
// Driver code
int main()
{
    int N = 6;
    int A[N] = { 1, 3, 2, 1, 2, 1 };
    cout <    return 0;
}

Java 语言(一种计算机语言,尤用于创建网站)

// Java implementation to find the number
// of subsets with equal bitwise AND,
// OR and XOR values
import java.io.*;
class GFG {
static int mod = 1000000007;
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int a[], int n)
{
    int answer = 0;
    // Traverse through all the subsets
    for (int i = 0; i <(1 <        int bitwiseAND = -1;
        int bitwiseOR = 0;
        int bitwiseXOR = 0;
        // Finding the subsets with the bits
        // of 'i' which are set
        for (int j = 0; j             // Computing the bitwise AND
            if ((i & (1 <                if (bitwiseAND == -1)
                    bitwiseAND = a[j];
                else
                    bitwiseAND &= a[j];
                // Computing the bitwise OR
                bitwiseOR |= a[j];
                // Computing the bitwise XOR
                bitwiseXOR ^= a[j];
            }
        }
        // Comparing all the three values
        if (bitwiseAND == bitwiseOR
            && bitwiseOR == bitwiseXOR)
            answer = (answer + 1) % mod;
    }
    return answer;
}
// Driver Code
public static void main (String[] args)
{
    int N = 6;
    int A[] = { 1, 3, 2, 1, 2, 1 };
    System.out.print(countSubsets(A, N));
}
}
// This code is contributed by shivanisinghss2110

Python 3

# Python3 implementation to find the number
# of subsets with equal bitwise AND,
# OR and XOR values
mod = 1000000007;
# Function to find the number of
# subsets with equal bitwise AND,
# OR and XOR values
def countSubsets(a, n) :
    answer = 0;
    # Traverse through all the subsets
    for i in range(1 <        bitwiseAND = -1;
        bitwiseOR = 0;
        bitwiseXOR = 0;
        # Finding the subsets with the bits
        # of 'i' which are set
        for j in range(n) :
            # Computing the bitwise AND
            if (i & (1 <                if (bitwiseAND == -1) :
                    bitwiseAND = a[j];
                else :
                    bitwiseAND &= a[j];
                # Computing the bitwise OR
                bitwiseOR |= a[j];
                # Computing the bitwise XOR
                bitwiseXOR ^= a[j];
        # Comparing all the three values
        if (bitwiseAND == bitwiseOR and bitwiseOR == bitwiseXOR) :
            answer = (answer + 1) % mod;
    return answer;
# Driver code
if __name__ == "__main__" :
    N = 6;
    A = [ 1, 3, 2, 1, 2, 1 ];
    print(countSubsets(A, N));
# This code is contributed by AnkitRai01

C

// C# implementation to find the number
// of subsets with equal bitwise AND,
// OR and XOR values
using System;
class GFG {
static int mod = 1000000007;
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int []a, int n)
{
    int answer = 0;
    // Traverse through all the subsets
    for (int i = 0; i <(1 <        int bitwiseAND = -1;
        int bitwiseOR = 0;
        int bitwiseXOR = 0;
        // Finding the subsets with the bits
        // of 'i' which are set
        for (int j = 0; j             // Computing the bitwise AND
            if ((i & (1 <                if (bitwiseAND == -1)
                    bitwiseAND = a[j];
                else
                    bitwiseAND &= a[j];
                // Computing the bitwise OR
                bitwiseOR |= a[j];
                // Computing the bitwise XOR
                bitwiseXOR ^= a[j];
            }
        }
        // Comparing all the three values
        if (bitwiseAND == bitwiseOR
            && bitwiseOR == bitwiseXOR)
            answer = (answer + 1) % mod;
    }
    return answer;
}
// Driver Code
public static void Main(String[] args)
{
    int N = 6;
    int []A = { 1, 3, 2, 1, 2, 1 };
    Console.Write(countSubsets(A, N));
}
}
// This code is contributed by 29AjayKumar

java 描述语言


Output: 

7

时间复杂度: O(N * 2 N ) 其中 N 是数组的大小。

辅助空间: O(1)

高效方法:高效方法的背后是按位运算的特性。


  • 利用按位 and 和按位 OR 的性质,我们可以说,如果 a & b == a | b,那么 a 等于 b。因此,如果子集的 AND 和 OR 值相等,那么子集的所有元素都是相同的(比如 x)。所以 AND 和 OR 值等于 x。

  • 因为子序列的所有值彼此相等,所以异或值出现两种情况:

    1. 子集大小为奇数:异或值等于 x。

    2. 子集大小为偶数:异或值等于 0。



  • 因此,从上面的观察,我们可以得出结论,所有奇数大小的子序列/子集具有相等的元素遵循该属性。

  • 除此之外,如果子集的所有元素都是 0,那么子集将遵循属性(与子集大小无关)。所以所有只有 0 作为元素的子集都会被添加到答案中。

  • 如果某个元素的频率为 K,那么它可以形成的奇数大小子集的数量为2K–1,它可以形成的非空子集的总数为2K–1

下面是上述方法的实现:

C++

// C++ program to find the number
// of subsets with equal bitwise
// AND, OR and XOR values
#include
using namespace std;
const int mod = 1000000007;
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
int countSubsets(int a[], int n)
{
    int answer = 0;
    // Precompute the modded powers
    // of two for subset counting
    int powerOfTwo[100005];
    powerOfTwo[0] = 1;
    // Loop to iterate and find the modded
    // powers of two for subset counting
    for (int i = 1; i <100005; i++)
        powerOfTwo[i]
            = (powerOfTwo[i - 1] * 2)
              % mod;
    // Map to store the frequency of
    // each element
    unordered_map frequency;
    // Loop to compute the frequency
    for (int i = 0; i         frequency[a[i]]++;
    // For every element > 0, the number of
    // subsets formed using this element only
    // is equal to 2 ^ (frequency[element]-1).
    // And for 0, we have to find all
    // the subsets, so 2^(frequency[element]) -1
    for (auto el : frequency) {
        // If element is greater than 0
        if (el.first != 0)
            answer
                = (answer % mod
                   + powerOfTwo[el.second - 1])
                  % mod;
        else
            answer
                = (answer % mod
                   + powerOfTwo[el.second]
                   - 1 + mod)
                  % mod;
    }
    return answer;
}
// Driver code
int main()
{
    int N = 6;
    int A[N] = { 1, 3, 2, 1, 2, 1 };
    cout <    return 0;
}

Java 语言(一种计算机语言,尤用于创建网站)

// Java program to find the number
// of subsets with equal bitwise
// AND, OR and XOR values
import java.util.*;
class GFG{
static int mod = 1000000007;
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int a[], int n)
{
    int answer = 0;
    // Precompute the modded powers
    // of two for subset counting
    int []powerOfTwo = new int[100005];
    powerOfTwo[0] = 1;
    // Loop to iterate and find the modded
    // powers of two for subset counting
    for (int i = 1; i <100005; i++)
        powerOfTwo[i]
            = (powerOfTwo[i - 1] * 2)
              % mod;
    // Map to store the frequency of
    // each element
    HashMap frequency = new HashMap();
    // Loop to compute the frequency
    for (int i = 0; i         if(frequency.containsKey(a[i])){
            frequency.put(a[i], frequency.get(a[i])+1);
        }else{
            frequency.put(a[i], 1);
    }
    // For every element > 0, the number of
    // subsets formed using this element only
    // is equal to 2 ^ (frequency[element]-1).
    // And for 0, we have to find all
    // the subsets, so 2^(frequency[element]) -1
    for (Map.Entry el : frequency.entrySet()) {
        // If element is greater than 0
        if (el.getKey() != 0)
            answer
                = (answer % mod
                   + powerOfTwo[el.getValue() - 1])
                  % mod;
        else
            answer
                = (answer % mod
                   + powerOfTwo[el.getValue()]
                   - 1 + mod)
                  % mod;
    }
    return answer;
}
// Driver code
public static void main(String[] args)
{
    int N = 6;
    int A[] = { 1, 3, 2, 1, 2, 1 };
    System.out.print(countSubsets(A, N));
}
}
// This code is contributed by 29AjayKumar

Python 3

# Python3 program to find the number
# of subsets with equal bitwise
# AND, OR and XOR values
mod = 1000000007
# Function to find the number of
# subsets with equal bitwise AND,
# OR and XOR values
def countSubsets(a, n):
    answer = 0
    # Precompute the modded powers
    # of two for subset counting
    powerOfTwo = [0 for x in range(100005)]
    powerOfTwo[0] = 1
    # Loop to iterate and find the modded
    # powers of two for subset counting
    for i in range(1, 100005):
        powerOfTwo[i] = (powerOfTwo[i - 1] * 2) % mod
    # Map to store the frequency of
    # each element
    frequency = {}
    # Loop to compute the frequency
    for i in range(0, n):
        if a[i] in frequency:
            frequency[a[i]] += 1
        else:
            frequency[a[i]] = 1
    # For every element > 0, the number of
    # subsets formed using this element only
    # is equal to 2 ^ (frequency[element]-1).
    # And for 0, we have to find all
    # the subsets, so 2^(frequency[element]) -1
    for key, value in frequency.items():
        # If element is greater than 0
        if (key != 0):
            answer = (answer % mod +
                  powerOfTwo[value - 1]) % mod
        else:
            answer = (answer % mod +
                 powerOfTwo[value] - 1 + mod)% mod
    return answer
# Driver code
N = 6
A = [ 1, 3, 2, 1, 2, 1 ]
print(countSubsets(A, N))
# This code is contributed by amreshkumar3

C

// C# program to find the number
// of subsets with equal bitwise
// AND, OR and XOR values
using System;
using System.Collections.Generic;
class GFG{
static int mod = 1000000007;
// Function to find the number of
// subsets with equal bitwise AND,
// OR and XOR values
static int countSubsets(int []a, int n)
{
    int answer = 0;
    // Precompute the modded powers
    // of two for subset counting
    int []powerOfTwo = new int[100005];
    powerOfTwo[0] = 1;
    // Loop to iterate and find the modded
    // powers of two for subset counting
    for(int i = 1; i <100005; i++)
       powerOfTwo[i] = (powerOfTwo[i - 1] * 2) % mod;
    // Map to store the frequency
    // of each element
    Dictionary frequency = new Dictionary();
    // Loop to compute the frequency
    for(int i = 0; i        if(frequency.ContainsKey(a[i]))
       {
           frequency[a[i]] = frequency[a[i]] + 1;
       }
       else
       {
           frequency.Add(a[i], 1);
       }
    // For every element > 0, the number of
    // subsets formed using this element only
    // is equal to 2 ^ (frequency[element]-1).
    // And for 0, we have to find all
    // the subsets, so 2^(frequency[element]) -1
    foreach (KeyValuePair el in frequency)
    {
        // If element is greater than 0
        if (el.Key != 0)
            answer = (answer % mod +
                      powerOfTwo[el.Value - 1]) % mod;
        else
            answer = (answer % mod +
                      powerOfTwo[el.Value] - 1 +
                      mod) % mod;
    }
    return answer;
}
// Driver code
public static void Main(String[] args)
{
    int N = 6;
    int []A = { 1, 3, 2, 1, 2, 1 };
    Console.Write(countSubsets(A, N));
}
}
// This code is contributed by Rajput-Ji

java 描述语言


Output: 

7

时间复杂度: O(N) ,其中 N 是数组的大小。

辅助空间: O(N + 10 5


推荐阅读
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文介绍了如何在给定的有序字符序列中插入新字符,并保持序列的有序性。通过示例代码演示了插入过程,以及插入后的字符序列。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 展开全部下面的代码是创建一个立方体Thisexamplescreatesanddisplaysasimplebox.#Thefirstlineloadstheinit_disp ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • [大整数乘法] java代码实现
    本文介绍了使用java代码实现大整数乘法的过程,同时也涉及到大整数加法和大整数减法的计算方法。通过分治算法来提高计算效率,并对算法的时间复杂度进行了研究。详细代码实现请参考文章链接。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • Java自带的观察者模式及实现方法详解
    本文介绍了Java自带的观察者模式,包括Observer和Observable对象的定义和使用方法。通过添加观察者和设置内部标志位,当被观察者中的事件发生变化时,通知观察者对象并执行相应的操作。实现观察者模式非常简单,只需继承Observable类和实现Observer接口即可。详情请参考Java官方api文档。 ... [详细]
  • Java序列化对象传给PHP的方法及原理解析
    本文介绍了Java序列化对象传给PHP的方法及原理,包括Java对象传递的方式、序列化的方式、PHP中的序列化用法介绍、Java是否能反序列化PHP的数据、Java序列化的原理以及解决Java序列化中的问题。同时还解释了序列化的概念和作用,以及代码执行序列化所需要的权限。最后指出,序列化会将对象实例的所有字段都进行序列化,使得数据能够被表示为实例的序列化数据,但只有能够解释该格式的代码才能够确定数据的内容。 ... [详细]
  • PHP中的单例模式与静态变量的区别及使用方法
    本文介绍了PHP中的单例模式与静态变量的区别及使用方法。在PHP中,静态变量的存活周期仅仅是每次PHP的会话周期,与Java、C++不同。静态变量在PHP中的作用域仅限于当前文件内,在函数或类中可以传递变量。本文还通过示例代码解释了静态变量在函数和类中的使用方法,并说明了静态变量的生命周期与结构体的生命周期相关联。同时,本文还介绍了静态变量在类中的使用方法,并通过示例代码展示了如何在类中使用静态变量。 ... [详细]
  • 预备知识可参考我整理的博客Windows编程之线程:https:www.cnblogs.comZhuSenlinp16662075.htmlWindows编程之线程同步:https ... [详细]
  • JDK源码学习之HashTable(附带面试题)的学习笔记
    本文介绍了JDK源码学习之HashTable(附带面试题)的学习笔记,包括HashTable的定义、数据类型、与HashMap的关系和区别。文章提供了干货,并附带了其他相关主题的学习笔记。 ... [详细]
author-avatar
holygame
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有