http://hihocoder.com/problemset/problem/1289?sid=763673
描述:
Little Hi runs a web server. Sometimes he has to deny access from a certain set of malicious IP addresses while his friends are still allow to access his server. To do this he writes N rules in the configuration file which look like:
allow 1.2.3.4/30 deny 1.1.1.1 allow 127.0.0.1 allow 123.234.12.23/3 deny 0.0.0.0/0
Each rule is in the form: allow | deny address or allow | deny address/mask.
When there comes a request, the rules are checked in sequence until the first match is found. If no rule is matched the request will be allowed. Rule and request are matched if the request address is the same as the rule address or they share the same first mask digits when both written as 32bit binary number.
For example IP "1.2.3.4" matches rule "allow 1.2.3.4" because the addresses are the same. And IP "128.127.8.125" matches rule "deny 128.127.4.100/20" because 10000000011111110000010001100100 (128.127.4.100 as binary number) shares the first 20 (mask) digits with10000000011111110000100001111101 (128.127.8.125 as binary number).
Now comes M access requests. Given their IP addresses, your task is to find out which ones are allowed and which ones are denied.
输入
Line 1: two integers N and M.
Line 2-N+1: one rule on each line.
Line N+2-N+M+1: one IP address on each line.
All addresses are IPv4 addresses(0.0.0.0 - 255.255.255.255). 0 <= mask <= 32.
For 40% of the data: 1 <= N, M <= 1000.
For 100% of the data: 1 <= N, M <= 100000.
输出
For each request output "YES" or "NO" according to whether it is allowed.
样例输入5 5
allow 1.2.3.4/30
deny 1.1.1.1
allow 127.0.0.1
allow 123.234.12.23/3
deny 0.0.0.0/0
1.2.3.4
1.2.3.5
1.1.1.1
100.100.100.100
219.142.53.100
样例输出
YES
YES
NO
YES
NO
插入:每次插入到一个节点,mask其实也就是深度,不输入mask时默认是32,TrieNode中的hasState表示这个节点有没有状态标记。
状态:TrieNode中的index记录是第几个规则,state记录是allow还是deny。
查找:往下search到叶节点的过程中取所有有状态标记的节点的规则号最小的那个的state。
一个细节:考虑规则中有mask为0的情况。
C++代码:
#include
#include
using namespace std;
typedef long long ll;
char c,type[10];
int n,m;
int num1,num2,num3,num4;
int zeroMask=-1;
struct TrieNode{
TrieNode* next[2];
bool state;
int index;
bool hasState;
TrieNode(){
next[0]=NULL;
next[1]=NULL;
hasState=false;
index=-1;
}
};
TrieNode* root;
void insert(ll ads,int index,int mask,bool state){
TrieNode* tmp=root;
int tag;
ll pst=(ll)1<<31;
for(int i=0;i0);
if(tmp->next[tag]==NULL)
tmp->next[tag]=new TrieNode();
tmp=tmp->next[tag];
pst>>=1;
}
if(tmp->index==-1){
tmp->index=index;
tmp->state=state;
}
tmp->hasState=true;
}
bool search(ll ads){
TrieNode* tmp=root;
ll pst=(ll)1<<31;
int ind=-1;
bool sta=true;
for(int i=0;i<32;i++){
int tag;
tag=((ads&pst)>0);
if(tmp->next[tag]==NULL)
break;
if(tmp->next[tag]->hasState){
if(ind==-1||tmp->next[tag]->indexnext[tag]->index;
sta=tmp->next[tag]->state;
}
}
tmp=tmp->next[tag];
pst>>=1;
}
if(ind==-1){
if(zeroMask!=0)
return true;
else return false;
}
return sta;
}
int main(){
root=new TrieNode();
scanf("%d%d",&n,&m);
ll address;
int state,mask;
for(int i=0;i