差分数组
我们在每一次输入的时候,若 x = i x=i x=i ( x x x 为输入的数)可以直接 c o n t i n u e continue continue (因为是求最小值),若是 x ! = i x!=i x!=i ,先存下来二者中的最大以及最小,并记录差分数组。
为什么用差分数组?
因为我们发现,如果将 i i i 到 j j j 中的数排序,那么其中每一个数的贡献都是 1 ,我们用差分数组存下来,最后求前缀和。若一个点的差分数组不为零,我们就可以 a n s + + ans++ ans++ ,无需考虑它差分数组具体的值(因为是求最小值)。
C o d e Code Code
#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——