#K40302. Count IP Addresses in Subnets

    ID: 26612 Type: Default 1000ms 256MiB

Count IP Addresses in Subnets

Count IP Addresses in Subnets

Given a list of IPv4 addresses and a list of subnets in CIDR notation, your task is to determine how many of the IP addresses fall within each subnet.

For a subnet \( S \) defined in CIDR notation as \( A/B \), an IP address \( ip \) is said to belong to \( S \) if its 32-bit unsigned integer representation, when bitwise ANDed with a mask \( M \) (derived from \( B \)), equals the network address \( A \) (also masked with \( M \)). Formally, for each subnet \( S_i \):

\[ \text{count}_i = \sum_{\text{ip} \in \text{IP addresses}} \mathbf{1}_{\{(\text{ip} \,\&\, M) = (A_i \,&\, M)\}} \]

You should read input from stdin and write the result to stdout.

inputFormat

The input is read from standard input (stdin) and has the following format:

  1. The first line contains two integers \(n\) and \(m\) separated by a space, where \(n\) is the number of IP addresses and \(m\) is the number of subnets.
  2. The next \(n\) lines each contain a single IPv4 address.
  3. The following \(m\) lines each contain a subnet in CIDR notation.

outputFormat

Output a single line containing \(m\) integers. The \(i\)-th integer should be the count of IP addresses that fall within the \(i\)-th subnet. The counts should be separated by a space.

## sample
4 2
192.168.1.1
192.168.1.2
192.168.2.1
10.0.0.1
192.168.1.0/24
10.0.0.0/8
2 1