文章目錄
1. 題目描述
1.1. Limit
Time Limit: 2000 ms
Memory Limit: 1024 MB
1.2. Problem Description
The Kingdom of Takahashi has towns, numbered through .
There is one teleporter in each town. The teleporter in Town sends you to Town .
Takahashi, the king, loves the positive integer . The selfish king wonders what town he will be in if he starts at Town and uses a teleporter exactly times from there.
Help the king by writing a program that answers this question.
1.3. Input
1.4. Constraints
1.5. Output
Print the integer representing the town the king will be in if he starts at Town and uses a teleporter exactly 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 and use the teleporter 5 times, our travel will be as follows: .
1.8. Sample Input 2
6 727202214173249351
6 5 2 5 3 2
1.9. Sample Output 2
2
1.10. Source
2. 解讀
將所有路徑使用鄰接表進行存儲,然後對路徑依次進行遍歷,將遍歷過的節點存儲在棧中,找出圖中的環路。
在節點入棧前,判斷其是否在棧中,若在,則該節點首次出現的位置到棧頂位置之間的節點所連成的邊即爲我們要找的環路,求出環路長度。
判斷 遊走次數 是否大於圖的起點 到環路起點 的距離 。
若 ,則輸出 中從 開始計數第 個元素。
若 ,則輸出 中從 開始計數第 個元素。
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,有問題歡迎通過郵箱交流。