function [obj,y] = iterative_LP(dists, svar, ustar, ds, Fs, Bs, k)
% The LP that is solved in each iteration of the iterative algorithm.

numPoints = size(dists, 1);
numCenters = size(dists, 2);

obj = optimvar('t');
centerVars = optimvar('y',[size(dists,2),1],'LowerBound',0.0,'UpperBound',1.0);

prob = optimproblem('Objective',obj,'ObjectiveSense','min');

groups = unique(svar);
groupNums = zeros(length(groups), 1);
groupIndics = zeros(numPoints, length(groups));
groupConstraints = optimconstr(length(groups),1);
for i = 1:length(groups)
    groupIndics(:,i) = svar == groups(i);
    groupNums(i) = sum(groupIndics(:,i));
    groupConstraints(i) = (sum(sum(dists .* repmat(ustar.*groupIndics(:,i),1,numCenters) .* Fs .* repmat(centerVars',numPoints,1))) ...
        + sum(sum(dists .* repmat((1-ustar).*groupIndics(:,i),1,numCenters) .* Bs .* repmat(centerVars',numPoints,1))) ...
        + sum(ds .* (1 - ustar) .* groupIndics(:,i) .* (1-sum(Bs .* repmat(centerVars',numPoints,1),2)))) / groupNums(i) <= obj;
end
prob.Constraints.groupConstraints = groupConstraints;
prob.Constraints.c2 = sum(centerVars) == k;
prob.Constraints.ustar = Fs(ustar==1,:) * centerVars == 1;
prob.Constraints.uf = Bs(ustar==0,:) * centerVars <= 1;

problem = prob2struct(prob);

[sol,~,~,~] = cplexlp(problem);

obj = sol(1);
y = sol(2:end);

end

