H.蹦床跳跃(Jump Conveyor)

题目描述
Emma is a creative child who got bored during the quarantine season. She set up n trampolines in a line inside the living room, each aimed in a particular direction. The ith trampoline has value vi.
When Emma jumps to position i, if there is a trampoline, she will jump to position i+vi. Of course, this could result in infinite jumping.

The Problem
Emma’s younger brother, Oliver, is very concerned for his sister’s safety. He would like to determine how many trampolines are unsafe for Emma to jump on initially. A trampoline is unsafe if it leads to infinite jumping.
输入
The first line of input will contain a single positive integer, t (t≤ 20), representing the number of input cases to process. The input cases follow. The first line of each input case contains a single
positive integer, n(1 ≤ n ≤ 1,000,000) representing the number of trampolines. Then, a single line follows with n integers, the values |vi| ≤ 109 for each trampoline.
输出
For each case, output a single line with a single integer representing the answer to the input case.
样例输入
2
7
1 -2 3 -1 2 -2 -2
5
4 2 5 -1 -3
样例输出
5
0

题目大意
给定一个数组,以数组的每一个数为起点开始跳,跳到的位置是当前的i + a[i],问会使得在数组中无限跳的起点有多少个。
思路
并查集维护即可,先将两个端点0,n + 1设置出来,代表两种能跳出的情况,然后扫一遍数组,每次找出当前的点的下一步是哪一个点,然后讲当前的点集的祖宗节点变成下一步的点的祖宗节点,即p[find(i)] = find(ne),最后扫一遍找出祖宗节点在1到n之间的点有多少个即可。
代码

#include <iostream>

using namespace std;

const int N = 1000010;

int p[N];
int a[N];

int find(int x)
{
    if (x != p[x]) p[x] = find(p[x]);
    return p[x];
}

int main()
{
    int t;
    scanf("%d", &t);
    while (t -- )
    {
        int n;
        scanf("%d", &n);
        for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
    
        for (int i = 0; i <= n + 1; i ++ ) p[i] = i;  // 两端也初始化,方便判断
        for (int i = 1; i <= n; i ++ )
        {
            int ne = i + a[i];  // 找出下一步在哪
            
            // 防止数组越界,每一边出界的情况归为一类
            if (ne > n) ne = n + 1;
            if (ne < 1) ne = 0;
            
            int pa = find(i), pb = find(ne);
            p[pa] = pb;  // 刚才找的点集都加到这个点下
        }
        
        int ans = 0;
        for (int i = 1; i <= n; i ++ )
        {
            int x = find(i);
            if (x >= 1 && x <= n) ans ++ ;
        }
        
        printf("%d\n", ans);
    }
    
    return 0;
}
上一篇:LCA(最近公共祖先)问题


下一篇:c#word转换pdf