给定大小为N的数组A ,其中, 。任务是找到所有可能的子阵列,然后将这些结果或所有的OR。
例子:
Input : 1 4 6
Output : 7
All possible subarrays are
{1}, {1, 4}, {4, 6} and {1, 4, 6}
ORs of these subarrays are 1, 5, 6
and 7. OR of these ORs is 7.
Input : 10 100 1000
Output : 1006
方法:在SET 1中,我们看到了如何找到所有可能的子数组的按位与。类似的方法在这里也适用。
朴素的解决办法是找到所有的子阵列,然后输出其结果的OR的OR。这将导致O(N 2 )解。
高效的解决方案:使用 i:e不管元素出现多少次,它的ORing都将被视为一个。因此,我们的问题归结为找到数组所有元素的OR 。
下面是上述方法的实现。
C++
// C++ program to find OR of all the sub-arrays
#include
using namespace std;
// function to return OR of sub-arrays
int OR(int a[], int n)
{
int ans = a[0];
for (int i = 1; i < n; ++i)
ans |= a[i];
return ans;
}
// Driver program
int main()
{
int a[] = { 1, 4, 6 };
int n = sizeof(a) / sizeof(a[0]);
// print OR of all subarrays
cout << OR(a, n);
return 0;
}
Java
// Java program to find OR of
// all the sub-arrays
class GFG
{
// function to return OR
// of sub-arrays
static int OR(int a[],int n)
{
int ans = a[0];
int i;
for(i = 1; i < n; i++)
{
ans |= a[i];
}
return ans;
}
// Driver Code
public static void main(String args[])
{
int a[] = { 1, 4, 6};
int n = a.length;
// print OR of all subarrays
System.out.println(OR(a, n));
}
}
// This code is contributed
// by ANKITRAI1
Python3
# Python3 program to find OR of all the sub-arrays
# function to return OR of sub-arrays
def OR(a, n):
ans = a[0]
for i in range(1,n):
ans |= a[i]
return ans
# Driver Code
if __name__=='__main__':
a = [1, 4, 6]
n = len(a)
# print OR of all subarrays
print(OR(a, n))
# This code is contributed
# by Shashank_Sharma
C#
// C# program to find OR of
// all the sub-arrays
using System;
class GFG
{
// function to return OR
// of sub-arrays
static int OR(int[] a, int n)
{
int ans = a[0];
int i;
for(i = 1; i < n; i++)
{
ans |= a[i];
}
return ans;
}
// Driver Code
public static void Main()
{
int[] a = { 1, 4, 6};
int n = a.Length;
// print OR of all subarrays
Console.Write(OR(a, n));
}
}
// This code is contributed
// by ChitraNayal
PHP
输出:
7
时间复杂度: O(N)