📜  不是任何其他给定列表的子集的列表计数

📅  最后修改于: 2021-04-23 20:46:15             🧑  作者: Mango

给定N个字符串列表,任务是查找不是任何其他给定列表的子列表的列表计数。

例子:

方法
请按照以下步骤解决问题:

  1. 首先,枚举所有向量中所有可能的字符串,即为它们分配一个整数。
  2. 然后,对所有单个列表使用位集来存储其中存在的字符串。
  3. 比较位集。如果其中一个位集是另一个位集的子集,请忽略该列表。否则,将该列表的索引插入集合中。
  4. 打印集中的所有索引。

下面的代码是上述方法的实现:

C++
// C++ program to find all lists
// which are not a subset of any
// other given lists
#include 
using namespace std;
  
#define N 50005
  
// Function to print all lists which
// are not a subset of any other lists
void findNonSubsets(vector >& v,
                    vector& ans)
{
    unordered_map mp;
    int id = 1;
    // Enumerate all strings
    // present in all lists
    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v[i].size(); j++) {
            if (mp.count(v[i][j]) > 0)
                continue;
  
            mp[v[i][j]] = id++;
        }
    }
  
    // Compute and store bitsets
    // of all strings in lists
    vector > v1;
  
    for (int i = 0; i < v.size(); i++) {
        bitset b;
        for (int j = 0; j < v[i].size(); j++) {
            b[mp[v[i][j]]] = 1;
        }
        v1.push_back(b);
    }
    for (int i = 0; i < v.size(); i++) {
        bool flag = false;
        for (int j = 0; !flag and j < v.size(); j++) {
            if (i != j) {
                // If one of the bitsets is
                // a subset of another, the
                // logical AND is equal to the
                // subset(intersection operation)
                if ((v1[i] & v1[j]) == v1[i]) {
                    flag = true;
                }
            }
        }
  
        if (!flag) {
            ans.push_back(i);
        }
    }
    return;
}
  
// Driver Program
signed main()
{
    vector > v
        = { { "hey", "hello", "hi" },
            { "hey", "bye" },
            { "hey", "hi" } };
  
    vector ans;
    findNonSubsets(v, ans);
  
    if (ans.size() == 0) {
        cout << -1 << endl;
        return 0;
    }
  
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
  
    return 0;
}


输出:
0 1

时间复杂度: O(N * M)
辅助空间: O(N * M)