bzoj 3037 贪心

时间:2023-03-08 15:38:21

我们可以贪心的分析,每个点的入度如果是0,那么这个点不可能

被用来更新答案,那么我们每次找入度为0的点,将他去掉,如果他连的

点没有被更新过答案,那么更新答案,去掉该点,环的时候最后处理就行了

/**************************************************************
    Problem:
    User: BLADEVIL
    Language: Pascal
    Result: Accepted
    Time: ms
    Memory: kb
****************************************************************/
 
//By BLADEVIL
var
    n, ans, cnt                 :longint;
    other, sum                  :array[..] of longint;
    flag                        :array[..] of boolean;
    que                         :array[..] of longint;
     
procedure init;
var
    i                           :longint;
begin
    readln(n);
    for i:= to n do
    begin
        read(other[i]);
        inc(sum[other[i]]);
    end;
end;
 
procedure main;
var
    h, t, cur                   :longint;
    i, j                        :longint;
     
begin
    t:=;
    for i:= to n do
    if sum[i]= then
    begin
        inc(t);
        que[t]:=i;
    end;
    h:=;
    while h<=t do
    begin
        cur:=que[h];
        inc(h);
        if (not flag[cur]) and (not flag[other[cur]]) then
        begin
            inc(ans);
            flag[other[cur]]:=true;
            dec(sum[other[other[cur]]]);
            if sum[other[other[cur]]]= then
            begin
                inc(t);
                que[t]:=other[other[cur]];
            end;
        end;
        flag[cur]:=true;
    end;
     
    for i:= to n do
        if  not flag[i] then
        begin
            cnt:=;
            flag[i]:=true;
            j:=i;
            while other[j]<>i do
            begin
                flag[other[j]]:=true;
                inc(cnt);
                j:=other[j];
            end;
            inc(ans,cnt div );
        end;
    writeln(ans);
end;
 
begin
    init;
    main;
end.