在C ++中查找等价类数的有效方法

时间:2014-08-11 03:50:40

标签: c++ arrays algorithm

假设我们得到了一个整数数组。例如A [n]

 A[11]={10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}

和素数列表,例如B [k]

 B[2]={3, 5}

对于B [k]中的每个元素b_i,我们发现A [n]中可被它整除的元素并将它们组合成等价类,并且如果A [n]中的元素不能被任何元素整除在B [k]中的元素,那么它是由单个元素组成的等价类。例如,在上面的例子中,等价类将是

 {12, 15, 18}
 {10, 15, 20}
 {11}
 {13}
 {14}
 {16}
 {17}
 {19}

(15被重复,因为它可以被3和5整除),其中第一个等价类由A [n]中的数字组成3,第二个是可被5整除的数字,其余的是co的元素-prime到3和5.基本上,给定A [n]和B [k],我想计算可以创建多少个等价集,在上面的例子中,它将是8。

我想出的是以下内容:

   for(j=0; j<n; j++){
       check[j]=true;
   }

   for(i=0; i<k; i++){
       helper=0;
       for(j=0; j<n; j++){
           if(check[j]==true){
               if(A[j]%B[i]==0){
                   check[j]==false;
                   helper++;
               }
           }
       }

       if(helper>0){
           count++;
       }
   }

   for(j=0; j<n; j++){
       if(check[j]==true){
           count++;
       }
   }

check是布尔数组,如果它已经属于某个等价类,则返回false;如果它不属于等价类,则返回true。 这计算了可以被B [k]中的元素整除的等价集的数量,但现在,我不知道如何处理单例集,因为在循环之后,检查数组成员都被重置为true。

(我试过了

   for(j=0; j<n; j++){
      if(check[j]==true){
          count++;
      }
   }

在上述循环之后,但它只将n加到计数中)

有人可以帮我这个吗?有没有更有效的方法呢?另外,我应该怎么处理单身人士集?

感谢。

PS。由于15在2组中重复,因此从技术上讲它不是等价类。对不起。

1 个答案:

答案 0 :(得分:1)

使用标准容器重写相同的代码示例:

#include <iostream>
#include <map>
#include <set>

using namespace std;

int A[]= { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int B[]= { 3, 5 };

typedef set<int> row;

int
main()
{
  map<int, row> results;

  // Fill
  for (auto i = begin(A); i != end(A); ++i)
    for (auto j = begin(B); j != end(B); j++)
    {
      if (*i % *j)
        results[*i] = row();
      else
      {
        if (results.find(*j) == results.end())
          results[*j] = row();

        results[*j].insert(*i);
      }
    }

  // Cleanup
  for (auto j = begin(B); j != end(B); j++)
    for (auto i : results[*j])
      results.erase(i);

  // Dump
  for (auto i : results)
  {
    cout << "{ ";
    if (i.second.size())
      for (auto j = i.second.begin(), nocomma = --i.second.end(); j != i.second.end(); ++j)
        cout << *j  << (j == nocomma ? " " : ", ");
    else
      cout << i.first << " ";
    cout << "}" << endl;
  }

  return 0;
}

输出:

{ 12, 15, 18 }
{ 10, 15, 20 }
{ 11 }
{ 13 }
{ 14 }
{ 16 }
{ 17 }
{ 19 }
相关问题