The computers are numbered from to . Since n \le 10^9, store the status of working and failed computers in a map map<int, int> m. The value of m[i] = 0 if the computer with number is working, and m[i] = 1 if it is broken. Initially, for all 1 \le i \le n, set m[i] = 0
For convenience, we introduce two dummy broken computers with numbers and n + 1. Set m[0] = m[n + 1] = 1.
The number of groups of computers in the network will be maintained in the variable . Initially, there is one group in the network, so set cnt = 1.
Now let's consider the process of handling queries. In particular, let's examine the failure of the computer with number (query type t = 1):
If both the computer's neighbors, on the right and left, are broken, the number of groups decreases by . This is because computer , which previously represented a group of a single device, has failed.
If both the computers to the right and left of computer are working, the number of groups will increase by .
In all other cases, the number of groups remains unchanged.
For processing a query of type t = 2, it is sufficient to print the current value of the variable .
Example
Algorithm implementation
Declare a data structure map.
map<int, int> m;Read the number of computers and the number of queries .
scanf("%d %d", &n, &q);Initialize the dummy computers with numbers and n + 1.
m[0] = 1;
m[n + 1] = 1;Maintain the number of groups of computers in the network in the variable . Initially, all computers are operational, so cnt = 1.
cnt = 1;Sequentially process queries.
while (q--)
{
scanf("%d", &t);
if (t == 1)
{Query t = 1. The computer with number fails. If computer is already broken, no action is required.
scanf("%d", &l);
if (m[l] == 0)
{Otherwise, set the state of computer as broken.
m[l] = 1;Depending on the state of the neighboring computers of (either working or broken), recompute the number of groups:
If both neighboring computers are broken, decrease by ;
If both neighboring computers are working, increase by ;
k = m[l - 1] + m[l + 1];
if (k == 2) cnt--;
else if (k == 0) cnt++;
}
}
elseFor query t = 2, print the current number of groups of computers in the network.
printf("%d\n", cnt);
}