ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

H.蹦床跳跃(Jump Conveyor)

2021-04-10 15:32:21  阅读:163  来源: 互联网

标签:Conveyor int line ne Jump single input 蹦床 find


题目描述
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;
}

标签:Conveyor,int,line,ne,Jump,single,input,蹦床,find
来源: https://www.cnblogs.com/lautoh/p/14640954.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有