% MC2 algorithm
%------------------------------------------------------------
R = 5;

pi_mc2 = zeros(1,n);

count = 0;
time = 0;
for i = 1:n % Fix initial node
    for j = 1:R % Iterations
        tic;
        
        % Random surfer (MC2)
        xi = i; 
        while(rand>eps) % Keep on surfing
           p = cumsum(P(xi,:));
           xi = find(rand<p,1);
        end
        pi_mc2(xi) = pi_mc2(xi) + 1;
        
        time  = time + toc;
        count = count + 1;
    end
end
fprintf('MC2 with R=%d: %.3f ms per walk, %.3f ms total\n',...
    R,time/count*1e3,time*1e3);

% Normalize result
pi_mc2 = 1/(n*R)*pi_mc2;

% Compute errors
for c = [10 30 50 100]
    e = abs(pi(rank(1:c))-pi_mc2(rank(1:c)));
    fprintf('Top-%d error: %.3f\n',c,mean(e));
end