% MC3 algorithm
%------------------------------------------------------------
R = 5;

pi_mc3 = zeros(1,n);

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

% Normalize result
pi_mc3 = eps/(n*R)*pi_mc3;

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