【问题标题】:Reducing the time complexity of the program降低程序的时间复杂度
【发布时间】:2020-09-15 20:00:18
【问题描述】:

我正在做这个练习题,给定一个由小写字母组成的字符串s 和一个位置p,我必须打印在位置p 出现的所有字母,这些字母出现在位置p 之前.

例如:如果字符串是“abaac”且 p=3(基于 1 的索引),则输出为 1,因为 'a' 出现在位置 p 之前一次。

有 q 个查询每个都给我一个位置 p。有没有办法让这段代码更有效率?
我正在使用我认为非常有效的散列?有没有我不知道的算法?

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    string s;
    cin>>s;
    int q;
    cin>>q;
    while(q--)
    {
        int p;
        cin>>p;
        int freq[26] = {0};
        for(int i = 0; i<(p-1); i++)
            freq[s[i]-'a']++;
        cout<<freq[s[p-1]-'a']<<"\n";
    }

}

【问题讨论】:

    标签: c++ c++11 hashmap time-complexity


    【解决方案1】:

    仅提示

    这里的诀窍是在您阅读字符串后预先计算答案。你可以很快做到。 因此,作为内存复杂度的交换,您将获得时间复杂度。 这可以在字符串大小的线性时间内完成。

    这样,您将能够在恒定时间内提供后续查询的答案。

    离题

    这个问题应该有这个代码来提高 IO 速度:

    int main()
    {
        std::sync_with_stdio(false);
        std::cin.tie(nullptr);
    

    【讨论】:

      【解决方案2】:

      您可以在每次查询之前从字符串计算一次解决方案。 所以每个查询都在 O(1) 中。

      std::vector<std::size_t> build_res(const std::string& s)
      {
          std::vector<std::size_t> res;
          int freq[26] = {0};
      
          for (auto c : s) {
              res.push_back(freq[c - 'a']++); // Assuming a-z contiguous (as in ASCII)
          }
          return res;
      }
      
      int main()
      {
          int n;
          std::cin >> n;
          std::string s;
          std::cin >> s;
          const auto res = build_res(s);
          int q;
          std::cin >> q;
          while (q--)
          {
              int p;
              std::cin >> p;
              std::cout << res[p - 1] << '\n';
          }
      }
      

      【讨论】:

      • 这是给鱼而不是鱼竿。
      • @MarekR:OP 已经提供了每个元素。
      【解决方案3】:

      您的代码目前所做的远远超出了必要的范围。在伪代码中你做

      while(q--)
      {
          read p
          freq[character] = determine count of any character up to position p
          print freq[character at position p]
      }
      

      对于每个单个查询,您重复计算每个字符在位置 p 之前出现的频率的整个过程,但随后您只使用单个字符的信息。那不是很有效。相反,您应该这样做:

      freq[position] = determine occurences of character at each position
      while(q--)
      {
          read p
          print freq[p]
      }
      

      第一部分可以通过遍历输入字符串一次来完成,然后对于每个查询,您只需从表中查找结果。

      【讨论】:

      • freq[character][position]?
      • @MarekR 嗯?哪一个?
      • 我的意思是我看不出任何地方都需要这个表达式。只有一个索引需要字符异或位置。
      • 我该如何实现这个?我仅在 while 循环内获得 p 的值。
      • @MarekR 哦,对了,我认为需要一个 2d 查找表,会解决这个问题
      猜你喜欢
      • 1970-01-01
      • 2016-01-08
      • 2015-12-01
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-28
      • 2016-10-07
      相关资源
      最近更新 更多