Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- typedef pair<int, int> pii;
- typedef long long ll;
- const int mn = 1e5 + 10;
- const ll mod = 998244353;
- int b[mn], c[mn], n, m;
- vector<vector<int> > path;
- vector<vector<int> > cycle;
- bool incyc[mn];
- pii loc[mn];
- bool vis[mn];
- bool ts[mn];
- int hd;
- void dfs(int x)
- {
- vis[x] = ts[x] = 1;
- if (ts[c[x]])
- hd = c[x], cycle.push_back({});
- else if (!vis[c[x]]) {
- dfs(c[x]);
- }
- if (hd) {
- cycle[cycle.size() - 1].push_back(x);
- loc[x] = { cycle.size() - 1, cycle[cycle.size() - 1].size() - 1 };
- incyc[x] = 1;
- }
- if (hd == 0) {
- if (incyc[c[x]])
- path.push_back({ c[x], x });
- else
- path[loc[c[x]].first].push_back(x);
- loc[x] = { path.size() - 1, path[path.size() - 1].size() - 1 };
- }
- if (x == hd)
- hd = 0;
- ts[x] = 0;
- }
- int main()
- {
- int i;
- scanf("%d%d", &n, &m);
- for (i = 1; i <= m; i++)
- scanf("%d", b + i), c[i] = i;
- for (i = 1; i <= m; i++)
- c[b[i]] = c[i];
- for (i = 1; i <= m; i++)
- c[i]++;
- c[m + 1] = m + 1;
- for (i = 1; i <= m; i++)
- if (!vis[i])
- dfs(i);
- ll C, cur = 1, ans = 0;
- scanf("%lld", &C);
- for (i = 1; i <= n; i++) {
- ll v;
- cur = cur * C % mod;
- int st = 1, rem = min(i, n - m + 1);
- if (i > n - m)
- st = i - (n - m);
- if (incyc[st])
- v = cycle[loc[st].first][(loc[st].second - rem + cycle[loc[st].first].size() * 1000000LL) % cycle[loc[st].first].size()];
- else if (i <= loc[st].second)
- v = path[loc[st].first][loc[st].second - rem];
- else {
- rem -= loc[st].second;
- st = path[loc[st].first][0];
- if (st == m + 1)
- v = m + rem;
- else
- v = cycle[loc[st].first][(loc[st].second - rem + cycle[loc[st].first].size() * 1000000LL) % cycle[loc[st].first].size()];
- }
- ans = (ans + (v - 1) * cur) % mod;
- }
- if (ans < 0)
- ans += mod;
- printf("%lld", ans);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement