【问题标题】:Output of my solve(string a, string b) does not match expected output in Shuffle Hashing我的求解(字符串 a,字符串 b)的输出与随机散列中的预期输出不匹配
【发布时间】:2020-04-15 07:28:19
【问题描述】:

我们取密码p,由小写字母组成,将其中的字母随机打乱得到p′(p′仍然可以等于p); 生成两个随机字符串,由小写字母 s1 和 s2 组成(这些字符串中的任何一个都可以为空); 得到的哈希 h=s1+p′+s2,其中加法是字符串连接。 我们的输入必须是“否”。测试用例,

对于每个测试用例,一个密码和一个散列密码(在不同的行中), 每个测试用例的输出必须是“YES”或“NO”,具体取决于给定的哈希是否可以用给定的密码构造。

#include<iostream>
#include<vector>
#define forn(i,n) for(int i=0;i<n;i++)
using namespace std;

void solve(string p, string h) {
    vector<int> pcnt(26);
    int ps = p.size();
    int hs = h.size();
    forn(j, ps) {
        ++pcnt[p[j] - 'a'];
        forn(j, hs) {
            vector<int> hcnt(26);
            for (int m = j; m < j+ps; m++) {
                ++hcnt[h[m] - 'a'];
                if (pcnt == hcnt) {
                    puts ("YES");
                    return;
                }
            }
        }

    }

    puts("NO");

}

int main() {
    int t;
    cin >> t;
    forn(i, t) {
        string p, h;
        cin >> p >> h;
        solve(p, h);
    }
}

对于输入

1
one
zzonneyy

我的输出是

YES

我不知道为什么。请帮帮我? 这是关于 codeforces 问题的link

【问题讨论】:

  • 您是否逐步调试?

标签: c++ string function vector hash


【解决方案1】:

您的代码有几个问题。

  1. forn(j, hs) 被使用了两次,j 的范围很难 理解。
  2. (pcnt == hcnt) 第一个字符匹配后立即退出条件检查
  3. 使用混淆代码的宏。 #define forn(i,n) for(int i=0;i&lt;n;i++)Macro's are evil

找到下面的 sn-p 应该可以解决您的问题,

void solve (string p, string h)
{
  std::vector <int> pcnt (26);
  int ps = p.size ();
  int hs = h.size ();

  //To create a finger print for given password
  for (int j = 0; j < ps; ++j)
    {
      ++pcnt[p[j] - 'a'];
    }

  vector <int>hcnt (26);

  //Moving frame to check the matching finger print
  for (int i = 0; i < hs; ++i)
    {
      ++hcnt[h[i] - 'a'];    
      if (i - ps >= 0){
          --hcnt[h[i - ps] - 'a'];
        }

      if (pcnt == hcnt){
          puts ("YES");
          return;
        }
    }

  puts ("NO");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-19
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    相关资源
    最近更新 更多