function pi=tsp(N,rho,alpha,A,traj)
% finds a good tsp tour via CE
% traj=0 - use node transitions
% traj=1 - use node placement

[m,n]=size(A);
tol=0.005;
z=7;

kk=(1:n)';

% initial P

st=zeros(z,1);

Pold=zeros(n);
if (traj==0),
P=ones(n)*1/(n-1);
P=P-diag(diag(P));
else
P=ones(n)*1/n;
end

count=1;
while max(max(abs(P-Pold)))>tol,

for i=1:N,
if traj==0,
	X(i,:)=gtsp0(P);
else
X(i,:)=gtsp1(P);
end
if(traj==0),
S(i)=stsp(X(i,:),A);
else

y=X(i,:);

for zi=1:n,
        ki=y(zi);
x(ki)=zi;
end

Y(i,:)=x;

S(i)=stsp(x,A);

end

end
[S,I]=sort(S);
g=floor(rho*N);

if(traj==0),

for i=1:n,
	for j=1:n,
% portion of elite samples having a transition from i to j
                ss=0;
for k=1:g,
                ii=kk(X(I(k),:)==i);
                if(ii<n),
                    if(X(I(k),ii+1)==j),
ss=ss+1;
end
else
if(X(I(k),1)==j),
ss=ss+1;
end
end
end

		w(i,j)=ss/g;
end
end

else %traj==1, ie node placement

for i=1:n,
for j=1:n,

ss=0;
for k=1:g,
  ss=ss+(Y(I(k),i)==j);
end

w(i,j)=ss/g;

end
end

end

Pold=P;
P=alpha*w+(1-alpha)*P;
st(1:(z-1))=st(2:z);
st(z)=S(g);
[count,S(g),S(1)]
if (sum(st==st(z))==z),
break;
end
count=count+1;
end
if(traj==0),
pi=X(I(1),:);
else
pi=Y(I(1),:);
end
