Detect the Virus ZOJ - 3430 AC自动机
One day, Nobita found that his computer is extremely slow. After several hours' work, he finally found that it was a virus that made his poor computer slow and the virus was activated by a misoperation of opening an attachment of an email.
Nobita did use an outstanding anti-virus software, however, for some strange reason, this software did not check email attachments. Now Nobita decide to detect viruses in emails by himself.
To detect an virus, a virus sample (several binary bytes) is needed. If these binary bytes can be found in the email attachment (binary data), then the attachment contains the virus.
Note that attachments (binary data) in emails are usually encoded in base64. To encode a binary stream in base64, first write the binary stream into bits. Then take 6 bits from the stream in turn, encode these 6 bits into a base64 character according the following table:
That is, translate every 3 bytes into 4 base64 characters. If the original binary stream contains 3k + 1 bytes, where k is an integer, fill last bits using zero when encoding and append '==' as padding. If the original binary stream contains 3k + 2 bytes, fill last bits using zero when encoding and append '=' as padding. No padding is needed when the original binary stream contains 3k bytes.
Value | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Encoding | A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | a | b | c | d | e | f |
Value | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 |
Encoding | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | + | / |
For example, to encode 'hello' into base64, first write 'hello' as binary bits, that is: 01101000 01100101 01101100 01101100 01101111
Then, take 6 bits in turn and fill last bits as zero as padding (zero padding bits are marked in bold): 011010 000110 010101 101100 011011 000110 111100
They are 26 6 21 44 27 6 60 in decimal. Look up the table above and use corresponding characters: aGVsbG8
Since original binary data contains 1 * 3 + 2 bytes, padding is needed, append '=' and 'hello' is finally encoded in base64: aGVsbG8=
Section 5.2 of RFC 1521 describes how to encode a binary stream in base64 much more detailedly:
Click here to see Section 5.2 of RFC 1521 if you have interest
The Base64 Content-Transfer-Encoding is designed to represent
arbitrary sequences of octets in a form that need not be humanly
readable. The encoding and decoding algorithms are simple, but the
encoded data are consistently only about 33 percent larger than the
unencoded data. This encoding is virtually identical to the one used
in Privacy Enhanced Mail (PEM) applications, as defined in RFC 1421.
The base64 encoding is adapted from RFC 1421, with one change: base64
eliminates the "*" mechanism for embedded clear text. A 65-character subset of US-ASCII is used, enabling 6 bits to be
represented per printable character. (The extra 65th character, "=",
is used to signify a special processing function.) NOTE: This subset has the important property that it is
represented identically in all versions of ISO 646, including US
ASCII, and all characters in the subset are also represented
identically in all versions of EBCDIC. Other popular encodings,
such as the encoding used by the uuencode utility and the base85
encoding specified as part of Level 2 PostScript, do not share
these properties, and thus do not fulfill the portability
requirements a binary transport encoding for mail must meet. The encoding process represents 24-bit groups of input bits as output
strings of 4 encoded characters. Proceeding from left to right, a
24-bit input group is formed by concatenating 3 8-bit input groups.
These 24 bits are then treated as 4 concatenated 6-bit groups, each
of which is translated into a single digit in the base64 alphabet.
When encoding a bit stream via the base64 encoding, the bit stream
must be presumed to be ordered with the most-significant-bit first. That is, the first bit in the stream will be the high-order bit in
the first byte, and the eighth bit will be the low-order bit in the
first byte, and so on. Each 6-bit group is used as an index into an array of 64 printable
characters. The character referenced by the index is placed in the
output string. These characters, identified in Table 1, below, are
selected so as to be universally representable, and the set excludes
characters with particular significance to SMTP (e.g., ".", CR, LF)
and to the encapsulation boundaries defined in this document (e.g.,
"-"). Table 1: The Base64 Alphabet Value Encoding Value Encoding Value Encoding Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y The output stream (encoded bytes) must be represented in lines of no
more than 76 characters each. All line breaks or other characters
not found in Table 1 must be ignored by decoding software. In base64
data, characters other than those in Table 1, line breaks, and other
white space probably indicate a transmission error, about which a
warning message or even a message rejection might be appropriate
under some circumstances. Special processing is performed if fewer than 24 bits are available
at the end of the data being encoded. A full encoding quantum is
always completed at the end of a body. When fewer than 24 input bits
are available in an input group, zero bits are added (on the right)
to form an integral number of 6-bit groups. Padding at the end of
the data is performed using the '=' character. Since all base64
input is an integral number of octets, only the following cases can
arise: (1) the final quantum of encoding input is an integral
multiple of 24 bits; here, the final unit of encoded output will be
an integral multiple of 4 characters with no "=" padding, (2) the
final quantum of encoding input is exactly 8 bits; here, the final
unit of encoded output will be two characters followed by two "="
padding characters, or (3) the final quantum of encoding input is
exactly 16 bits; here, the final unit of encoded output will be three
characters followed by one "=" padding character. Because it is used only for padding at the end of the data, the
occurrence of any '=' characters may be taken as evidence that the
end of the data has been reached (without truncation in transit). No
such assurance is possible, however, when the number of octets
transmitted was a multiple of three. Any characters outside of the base64 alphabet are to be ignored in
base64-encoded data. The same applies to any illegal sequence of
characters in the base64 encoding, such as "=====" Care must be taken to use the proper octets for line breaks if base64
encoding is applied directly to text material that has not been
converted to canonical form. In particular, text line breaks must be
converted into CRLF sequences prior to base64 encoding. The important
thing to note is that this may be done directly by the encoder rather
than in a prior canonicalization step in some implementations. NOTE: There is no need to worry about quoting apparent
encapsulation boundaries within base64-encoded parts of multipart
entities because no hyphen characters are used in the base64
encoding.
Here is a piece of ANSI C code that can encode binary data in base64. It contains a function, encode (infile, outfile), to encode binary file infile in base64 and output result to outfile.
Click here to see the reference C code if you have interest
static const char cb64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
void encodeblock(unsigned char in[3], unsigned char out[4], int len) {
out[0] = cb64[ in[0] >> 2 ];
out[1] = cb64[ ((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4) ];
out[2] = (unsigned char) (len > 1 ? cb64[ ((in[1] & 0x0f) << 2) | ((in[2] & 0xc0) >> 6) ] : '=');
out[3] = (unsigned char) (len > 2 ? cb64[ in[2] & 0x3f ] : '=');
}
void encode(FILE *infile, FILE *outfile) {
unsigned char in[3], out[4];
int i, len;
while (!feof(infile)) {
len = 0;
for (i = 0; i < 3; i++) {
in[i] = (unsigned char) getc(infile);
if (!feof(infile)) {
len++;
} else {
in[i] = 0;
}
}
if (len) {
encodeblock(in, out, len);
for (i = 0; i < 4; i++) {
putc(out[i], outfile);
}
}
}
}
Input
Input contains multiple cases (about 15, of which most are small ones). The first line of each case contains an integer N (0 <= N <= 512). In the next N distinct lines, each line contains a sample of a kind of virus, which is not empty, has not more than 64 bytes in binary and is encoded in base64. Then, the next line contains an integer M (1 <= M <= 128). In the following M lines, each line contains the content of a file to be detected, which is not empty, has no more than 2048 bytes in binary and is encoded in base64.
There is a blank line after each case.
<h4< dd="">Output
For each case, output M lines. The ith line contains the number of kinds of virus detected in the ith file.
Output a blank line after each case.
<h4< dd="">Sample Input
3
YmFzZTY0
dmlydXM=
dDog
1
dGVzdDogdmlydXMu 1
QA==
2
QA==
ICAgICAgICA=
<h4< dd="">Sample Output
2 1
0
<h4< dd="">Hint
In the first sample case, there are three virus samples: base64, virus and t: , the data to be checked is test: virus., which contains the second and the third, two virus samples.
解码过程很恶心,不能用char存
题意:先给n串加密后的字符,然后m串加密后的字符,解码之后求n对应每个m的匹配数,很显然的ac自动机
加密过程是先用对应ascii表的标号来代替字符,然后把这些数字转换成8位的二进制,全部连起来,然后每6位算一个数,用二进制算成整数,最后用这些整数来映射给定的表
题解:反解密就好了,就是特别容易错
代码:
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std; struct Trie
{
int next[520*64][256],fail[520*64],end[520*64];
int root,L;
int newnode()
{
for(int i = 0;i < 256;i++)
next[L][i] = -1;
end[L++] = -1;
return L-1;
}
void init()
{
L = 0;
root = newnode();
}
void insert(unsigned char buf[],int len,int id)
{
int now = root;
for(int i = 0;i < len;i++)
{
if(next[now][buf[i]] == -1)
next[now][buf[i]] = newnode();
now = next[now][buf[i]];
}
end[now] = id;
}
void build()
{
queue<int>Q;
fail[root] = root;
for(int i = 0;i < 256;i++)
if(next[root][i] == -1)
next[root][i] = root;
else
{
fail[next[root][i]]=root;
Q.push(next[root][i]);
}
while(!Q.empty())
{
int now = Q.front();
Q.pop();
for(int i = 0;i < 256;i++)
if(next[now][i] == -1)
next[now][i] = next[fail[now]][i];
else
{
fail[next[now][i]] = next[fail[now]][i];
Q.push(next[now][i]);
}
}
}
bool used[520];
int query(unsigned char buf[],int len,int n)
{
memset(used,false,sizeof(used));
int now = root;
for(int i = 0;i < len;i++)
{
now = next[now][buf[i]];
int temp = now;
while( temp!=root )
{
if(end[temp] != -1)
used[end[temp]]=true;
temp = fail[temp];
}
}
int res = 0;
for(int i = 0;i < n;i++)
if(used[i])
res++;
return res;
}
}; unsigned char buf[2050];
int tot;
char str[4000];
unsigned char s[4000];
unsigned char Get(char ch)
{
if( ch>='A'&&ch<='Z' )return ch-'A';
if( ch>='a'&&ch<='z' )return ch-'a'+26;
if( ch>='0'&&ch<='9' )return ch-'0'+52;
if( ch=='+' )return 62;
else return 63;
}
void change(unsigned char str[],int len)
{
int t=0;
for(int i=0;i<len;i+=4)
{
buf[t++]=((str[i]<<2)|(str[i+1]>>4));
if(i+2 < len)
buf[t++]=( (str[i+1]<<4)|(str[i+2]>>2) );
if(i+3 < len)
buf[t++]= ( (str[i+2]<<6)|str[i+3] );
}
tot=t;
}
Trie ac;
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
int n,m;
while(scanf("%d",&n) == 1)
{
ac.init();
for(int i = 0;i < n;i++)
{
scanf("%s",str);
int len = strlen(str);
while(str[len-1]=='=')len--;
for(int j = 0;j < len;j++)
{
s[j] = Get(str[j]);
}
change(s,len);
ac.insert(buf,tot,i);
}
ac.build();
scanf("%d",&m);
while(m--)
{
scanf("%s",str);
int len=strlen(str);
while(str[len-1]=='=')len--;
for(int j = 0;j < len;j++)
s[j] = Get(str[j]);
change(s,len);
printf("%d\n",ac.query(buf,tot,n));
}
printf("\n");
}
return 0;
}
Detect the Virus ZOJ - 3430 AC自动机的更多相关文章
- HDU - 2222,HDU - 2896,HDU - 3065,ZOJ - 3430 AC自动机求文本串和模式串信息(模板题)
最近正在学AC自动机,按照惯例需要刷一套kuangbin的AC自动机专题巩固 在网上看过很多模板,感觉kuangbin大神的模板最为简洁,于是就选择了用kuangbin大神的模板. AC自动机其实就是 ...
- ZOJ - 3430 ac自动机
这题主要就是解码过程很恶心,不能用char存,一共wa了20发 题意:先给n串加密后的字符,然后m串加密后的字符,解码之后求n对应每个m的匹配数,很显然的ac自动机 加密过程是先用对应ascii表的标 ...
- Detect the Virus - ZOJ 3430(恶心的自动机)
题目大意:给你一些病毒的特征码,然后再给一些文本,判断每个文本有多少种病毒,不过给的字符串都是加密处理过的,给的每个字符串都有对应一个64以内的一个数(题目里面那个表就是),然后可以把这个64以内的这 ...
- ZOJ 3494 (AC自动机+高精度数位DP)
题目链接: http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3494 题目大意:给定一些被禁止的BCD码.问指定范围内不含有 ...
- BCD Code ZOJ - 3494 AC自动机+数位DP
题意: 问A到B之间的所有整数,转换成BCD Code后, 有多少个不包含属于给定病毒串集合的子串,A,B <=10^200,病毒串总长度<= 2000. BCD码这个在数字电路课上讲了, ...
- Searching the String ZOJ - 3228 AC自动机查询升级版
题意:先给你一个不超过1000000长度的大串s:接下来输入一个n代表接下来输入的小串个数,小串长度不超过6. 小串分两种类型0和1类型. 0类型表示小串在大串中的最大匹配个数就是常规的AC自动机的做 ...
- ZOJ - 3430 Detect the Virus —— AC自动机、解码
题目链接:https://vjudge.net/problem/ZOJ-3430 Detect the Virus Time Limit: 2 Seconds Memory Limit: 6 ...
- ZOJ 3430 Detect the Virus(AC自动机)
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3430 题意:给你n个编码后的模式串,和m个编码后的主串,求原来主 ...
- ZOJ 4114 Detect the Virus(AC自动机)
Detect the Virus Time Limit: 2 Seconds Memory Limit: 65536 KB One day, Nobita found that his co ...
随机推荐
- FlatBuffers使用小结
最近做一个Android APP,由于离线业务需求,需要在启动APP时候同步大量数据到APP上,遇到了JSON性能瓶颈.从下方的图片中可以看出,当使用 json 传输数据,在解析json的时候会产生大 ...
- 【Linux】dlopen failed: /lib/lsiRAID.so: cannot open shared object file: No such file or directory
遇到这个问题,首先第一反应,是看其他的服务器中是否有这个库文件,如果有的话直接cp过来一份就行 但是检查发现,其他的系统中也不存在lsiRAID.so这个库文件,很神奇.. 但是看日志持续报错,查看s ...
- 1.5V升3.3V芯片电路图,稳压3.3V供电MCU模块等
干电池1.5V可以升到3.3V,通过PW5100干电池升压IC,于外围3个元件:2个电容和一个电感即可组成1.5V升3.3V的电路系统. 干电池属于低能量的电池产品,不过一般使用到干电池的产品也是输出 ...
- Windows环境下搭建FTP服务器
Windows主机建立FTP服务器 第一步:启用对应的Windows功能 控制面板 选择启用或关闭Windows功能 勾选FTP服务器和Web管理工具 可能出现的问题 系统提示无法安装IIS和FTP服 ...
- B树、B+树索引算法原理(下)
B树.B+树索引算法原理(下) - codedump的网络日志 https://www.codedump.info/post/20200615-btree-2/
- django 请求处理流程 链路追踪
class BaseMiddleware: # https://github.com/django/django/blob/master/tests/utils_tests/test_decorato ...
- Buffer Data RDMA 零拷贝 直接内存访问
waylau/netty-4-user-guide: Chinese translation of Netty 4.x User Guide. 中文翻译<Netty 4.x 用户指南> h ...
- 七:Spring Security 前后端分离登录,非法请求直接返回 JSON
Spring Security 前后端分离登录,非法请求直接返回 JSON 解决方案 在 Spring Security 中未获认证的请求默认会重定向到登录页,但是在前后端分离的登录中,这个默认行为则 ...
- 深入理解java虚拟机,GC参考手册
深入理解java虚拟机 一.<深入理解Java虚拟机> 1.第2章 Java内存区域与内存溢出异常 2.第3章 垃圾收集器与内存分配策略 3.第4章 虚拟机性能监控与故障处理工具 4.第5 ...
- hadoop使用常见问题总结!
1,执行 hdfs dfs -copyFromLocal 命令报错! 19/01/02 11:01:32 INFO hdfs.DFSClient: Exception in createBlockOu ...