AtCoder 4804 Beginner Contest 167 D Teleporter 思維題

1. 題目描述

1.1. Limit

Time Limit: 2000 ms

Memory Limit: 1024 MB

1.2. Problem Description

The Kingdom of Takahashi has NN towns, numbered 11 through NN.

There is one teleporter in each town. The teleporter in Town ii (1iN)(1 \leq i \leq N) sends you to Town AiA_i.

Takahashi, the king, loves the positive integer KK. The selfish king wonders what town he will be in if he starts at Town 11 and uses a teleporter exactly KK times from there.

Help the king by writing a program that answers this question.


1.3. Input

NN KK
A1 A2  ANA_1\ A_2\ \dots \ A_N

1.4. Constraints

2N2×1052 \leq N \leq 2 \times 10^5

1AiN1 \leq A_i \leq N

1K10181 \leq K \leq 10^{18}


1.5. Output

Print the integer representing the town the king will be in if he starts at Town 11 and uses a teleporter exactly KK times from there.


1.6. Sample Input 1

4 5
3 2 4 1

1.7. Sample Output 1

4

If we start at Town 11 and use the teleporter 5 times, our travel will be as follows: 1341341 \to 3 \to 4 \to 1 \to 3 \to 4.

1.8. Sample Input 2

6 727202214173249351
6 5 2 5 3 2

1.9. Sample Output 2

2

1.10. Source

AtCoder 4804 Teleporter


2. 解讀

將所有路徑使用鄰接表進行存儲,然後對路徑依次進行遍歷,將遍歷過的節點存儲在棧StackStack中,找出圖中的環路。

在節點入棧前,判斷其是否在棧中,若在,則該節點首次出現的位置到棧頂位置之間的節點所連成的邊即爲我們要找的環路CC,求出環路長度SS

判斷 遊走次數 KK 是否大於圖的起點 Q0Q_0 到環路起點 W0W_0 的距離 length=Q0W0length = Q_0 - W_0

K>lengthK > length,則輸出 StackStack 中從 00 開始計數第 Q0+(KW0)%SQ_0 + (K - W_0) \% S 個元素。

KlengthK \le length,則輸出 StackStack 中從 00 開始計數第 KK 個元素。

3. 代碼

#include <iostream>
#include <string.h>
#include <vector>
using namespace std;

const int NUM = 2 * 10e5 + 1;
// 存儲
long long list[NUM];
// 標誌訪問
bool visit[NUM];
// 棧存儲訪問路徑
vector<long long> vec;

int main()
{
    // test case
    long long n, k;
    scanf("%lld %lld", &n, &k);
    // 初始化
    memset(list, 0, sizeof(list));
    memset(visit, 0, sizeof(visit));
    // 輸入
    for (long long i = 0; i < n; i++) {
        scanf("%lld", &list[i]);
    }
    // 初始化
    long long buffer = 1;
    // 計算
    for (int i = 0; i < n; i++) {
        // 標誌訪問
        visit[buffer] = 1;
        // 節點入棧
        vec.push_back(buffer);
        // 獲取下一個節點
        buffer = list[buffer - 1];
        // 若形成環路
        if (visit[buffer] == 1) {
            break;
        }
    }
    // 在棧中找出環路開始位置
    auto it = find(vec.begin(), vec.end(), buffer);
    // 環路長度
    long long cycleLength = vec.end() - it;
    // 環路開始前的棧深度
    long long stackLength = it - vec.begin();
    // 計算從環路起點開始的位移
    long long posMark;
    if (k > stackLength) {
        // 若存在環路
        posMark = (k - stackLength) % cycleLength;
    } else {
        // 若不存在環路
        posMark = (k - stackLength);
    }
    // 輸出
    printf("%lld\n", vec[stackLength + posMark]);
}

聯繫郵箱:[email protected]

Github:https://github.com/CurrenWong

歡迎轉載/Star/Fork,有問題歡迎通過郵箱交流。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章