AOJ1370: Hidden Anagrams(hash)
题意
Sol
直接对出现的次数hash即可,复杂度\(O(26n^2)\)
一开始没判长度条件疯狂wa
#include<bits/stdc++.h>
//#define int long long
#define LL long long
#define ull unsigned long long
using namespace std;
const int MAXN = 4001, mod = 1e9 + 7, INF = 1e9 + 10;
const double eps = 1e-9;
template <typename A, typename B> inline bool chmin(A &a, B b){if(a > b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline bool chmax(A &a, B b){if(a < b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline LL add(A x, B y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename A, typename B> inline void add2(A &x, B y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename A, typename B> inline LL mul(A x, B y) {return 1ll * x * y % mod;}
template <typename A, typename B> inline void mul2(A &x, B y) {x = (1ll * x * y % mod + mod) % mod;}
template <typename A> inline void debug(A a){cout << a << '\n';}
template <typename A> inline LL sqr(A x){return 1ll * x * x;}
inline int read() {
char c = getchar(); int x = 0, f = 1;
while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x * f;
}
int N, M;
char s1[MAXN], s2[MAXN];
map<ull, bool> mp;
ull base = 29;
int num[27];
ull get() {
ull now = 0;
for(int i = 0; i < 26; i++)
now = now * base + num[i];
return now;
}
signed main() {
scanf("%s", s1 + 1);
scanf("%s", s2 + 1);
N = strlen(s1 + 1); M = strlen(s2 + 1);
for(int len = min(N, M); len >= 1; len--) {
mp.clear();
memset(num, 0, sizeof(num));
for(int i = 1; i <= N; i++) {
num[s1[i] - 'a']++;
if(i > len) num[s1[i - len] - 'a']--;
if(i >= len) mp[get()] = 1;
}
memset(num, 0, sizeof(num));
for(int i = 1; i <= M; i++) {
num[s2[i] - 'a']++;
if(i > len) num[s2[i - len] - 'a']--;
if(i >= len && mp[get()]) {
cout << len << '\n';
return 0;
}
}
}
puts("0");
return 0;
}
作者:自为风月马前卒
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。