difference array
Every time we input, if x = ix=ix=i ( x x x is the input number) you can directlycontinue continuec o n t i n u e (because it is the minimum value), ifx ! = ix!=ix!=i , save the largest and smallest of the two first, and record the difference array.
Why use differential arrays?
Because we found that if iii tojjThe numbers in j are sorted, then the contribution of each number is 1, we use the difference array to save it, and finally calculate the prefix sum. If the difference array of a point is not zero, we canans + + ans++a n s++ , without considering the specific value of its difference array (because it is the minimum value).
C o d e CodeCode
#include<bits/stdc++.h>
using namespace std;
#define int long long
int t;
const int maxn = 1000005;
int n, a[maxn];
inline int read ()
{
int s = 0, x = 1;
char ch;
ch = getchar ();
while (ch < '0' or ch > '9')
{
if (ch == '-') x = -1;
ch = getchar ();
}
while (ch >= '0' and ch <= '9')
{
s = s * 10 + ch - '0';
ch = getchar ();
}
return s * x;
}
signed main ()
{
t = read ();
while (t--)
{
n = read ();
for (int i = 1; i <= n; i++) a[i] = 0;
for (int i = 1; i <= n; i++)
{
int x;
x = read ();
if (x == i) continue;
int maxx = max (x, i);
int minn = min (x, i);
a[maxx + 1]--;
a[minn]++;
}
int ans = 0;
for (int i = 1; i <= n; i++)
{
a[i] += a[i - 1];
if (a[i]) ans += 1;
}
printf ("%lld\n", ans);
}
return 0;
}
—— E n d End End——