bzoj 3037 贪心

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

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

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

/**************************************************************
    Problem: 3037
    User: BLADEVIL
    Language: Pascal
    Result: Accepted
    Time:1672 ms
    Memory:12920 kb
****************************************************************/
 
//By BLADEVIL
var
    n, ans, cnt                 :longint;
    other, sum                  :array[0..1000020] of longint;
    flag                        :array[0..1000020] of boolean;
    que                         :array[0..1000020] of longint;
     
procedure init;
var
    i                           :longint;
begin
    readln(n);
    for i:=1 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:=0;
    for i:=1 to n do
    if sum[i]=0 then
    begin
        inc(t);
        que[t]:=i;
    end;
    h:=1;
    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]]]=0 then
            begin
                inc(t);
                que[t]:=other[other[cur]];
            end;
        end;
        flag[cur]:=true;
    end;
     
    for i:=1 to n do
        if  not flag[i] then
        begin
            cnt:=1;
            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 2);
        end;
    writeln(ans);
end;
 
begin
    init;
    main;
end.

 

转载于:https://www.cnblogs.com/BLADEVIL/p/3496041.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值