不开O2过了 吸氧RE了
查看原帖
不开O2过了 吸氧RE了
424751
wumakanghui楼主2023/12/22 15:19

求指点一下为什么

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 1e6+10;

int n;
int p[N], stk[N];
bool st[N], in_stk[N];
// st[]是否遍历过,in_stk[]是否在栈中

int main()
{
    scanf("%d", &n);
    for (int i = 1; i <= n; i ++ ) scanf("%d", &p[i]);

    int res = n;
    for (int i = 1; i <= n; i ++ )
        if (!st[i])
        {
            int tt = 0;
            int j = i;
            while (!st[j])
            {
                stk[ ++ tt] = j;
                st[j] = true;
                in_stk[j] = true;
                j = p[j];
            }
            if (in_stk[j])
            {
                int cnt = 1;
                while (stk[tt] != j)
                {
                    in_stk[stk[tt -- ]] = false;
                    cnt ++ ;
                }
                res = min(res, cnt);
            }
            // while (tt)in_stk[stk[tt -- ]] = false;
        }
    printf("%d\n", res);
    return 0;
}

2023/12/22 15:19
加载中...