Exemplo n.º 1
0
int main( void )
{
	Fixed a(1);
	Fixed c(3);
	Fixed const b( Fixed( 5.05f ) * Fixed( 2 ) );
	Fixed const d( 18.56f );

	std::cout << "A = " << a << std::endl;
	std::cout << "B = " << b << std::endl;
	std::cout << "C = " << c << std::endl;
	std::cout << "D = " << d << std::endl;
	std::cout << "Ope + " << (a + c) << std::endl;
	std::cout << "Ope - " << (a - c) << std::endl;
	std::cout << "Ope * " << (a * c) << std::endl;
	std::cout << "Ope / " << (a / c) << std::endl;
	std::cout << "Ope > " << (a > c) << std::endl;
	std::cout << "Ope < " << (a < c) << std::endl;
	std::cout << "Ope >= " << (a >= c) << std::endl;
	std::cout << "Ope <= " << (a <= c) << std::endl;
	std::cout << "Ope == " << (a == c) << std::endl;
	std::cout << "Ope != " << (a != c) << std::endl;
	std::cout << "Max = " << Fixed::max( a, c ) << std::endl;
	std::cout << "Max = " << Fixed::max( b, d ) << std::endl;
	std::cout << "Min = " << Fixed::min( a, c ) << std::endl;
	std::cout << "Min = " << Fixed::min( b, d ) << std::endl;

	return 0;
}
Exemplo n.º 2
0
MapPoint MapManager::grid2pos(const MapGrid &grid) 
{
	MapPoint pos;
	pos.x = (grid.x+Fixed(0.5)) * m_data->m_gridW;
	pos.y = (grid.y+Fixed(0.5)) * m_data->m_gridH;
	return pos;
}
Exemplo n.º 3
0
void AudioMixer::setAudioVolume(int v)
{
  if (v>=0 &&
      v<=127)
    {
      volume=v;
      volumeFixed=Fixed(Fixed(v)/Fixed(127));
    }
  DPRINTF("AudioVolume:%d",volume);
}
Exemplo n.º 4
0
int main()
{
	std::cout 
		<< "3.2 + 4.5 = " << Fixed::FromFloat(3.2f) + Fixed::FromFloat(4.5f) << "\n" 
		<< "3 + 4 = " << Fixed(3) + Fixed(4) << "\n"
		<< "10/2 = " << Fixed(10) / Fixed(2) << "\n"
		<< "10/0.5 = " << Fixed(10) / Fixed::FromFloat(0.5f) << "\n"
		<< "sin(0) = " << sin(Fixed(0)) << "\n"
		<< "sin(pi/2) = " << sin(Fixed::FromFloat(3.1415926f / 2.0f)) << "\n"
		<< "cos(0) = " << cos(Fixed(0))  << "\n"
		<< "sqrt(10000) = " << sqrt(Fixed(10000)) << "\n"
		<< std::endl;
		
	for (double x = 0; x < M_PI / 2 + 0.5; x += 0.1) {
		// std::cout 
		// 	<< "tableSin( " << 360.0 * x / (2 * M_PI) << " degrees) = " << sin(Fixed(float(x))) << " "
		// 	<< "  actual = " << sin(x) << " \n";

		Fixed fx = Fixed::FromFloat(x);
		Fixed sinfx = sin(fx);
		//Fixed asinsinfx = asin(sinfx);
		
		std::cout << "sin( " << x << ") = " << sin(fx) << ", Correct answer is " << sin(x) /*<< ", asin = " << asin(sin(fx))*/ << "\n";			
//		std::cout << "cos( " << x << ") = " << cos(fx) /*<< ", acos = " << acos(cos(fx))*/ << "\n";			
	}
	
}
Exemplo n.º 5
0
int main( void ) {
	Fixed a;
	Fixed const b( Fixed( 5.05f ) * Fixed( 2 ) );
	Fixed const c( Fixed( 5.05f ) + Fixed( 2 ) );
	Fixed const d( Fixed( 5.05f ) - Fixed( 2 ) );
	Fixed const e( Fixed( 5.05f ) / Fixed( 2 ) );
	std::cout << "a : " << a << std::endl;
	std::cout << "++a : " << ++a << std::endl;
	std::cout << "a++ : " << a++ << std::endl;
	std::cout << "a : " << a << std::endl;
	std::cout << "b : " << b << std::endl;
	std::cout << "c : " << c << std::endl;
	std::cout << "d : " << d << std::endl;
	std::cout << "e : " << e << std::endl;
	
	std::cout << "max(a, b) : " << Fixed::max( a, b ) << std::endl;
	std::cout << "min(a, b) : " << Fixed::min( a, b ) << std::endl;

	std::cout << std::endl;

	std::cout << "a > b " << (a > b) << std::endl;
	std::cout << "a < b " << (a < b) << std::endl;
	std::cout << "a >= b " << (a >= b) << std::endl;
	std::cout << "a <= b " << (a <= b) << std::endl;
	std::cout << "a == c " << (a == c) << std::endl;
	std::cout << "a >= c " << (a >= c) << std::endl;
	std::cout << "a <= c " << (a <= c) << std::endl;
	return 0;
}
Exemplo n.º 6
0
int FixedOrCommonCandidates(Node * N)
{
    int Count = 0;

    Count = N->FixedTo2 ? 2 : N->FixedTo1 ? 1 : 0;
    if (MergeTourFiles >= 2) {
        if (!Fixed(N, N->MergeSuc[0]) && IsCommonEdge(N, N->MergeSuc[0]))
            Count++;
        if (!Fixed(N->MergePred, N) && IsCommonEdge(N->MergePred, N))
            Count++;
    }
    if (Count > 2)
        eprintf("Node %d has more than two required candidate edges",
                N->Id);
    return Count;
}
Exemplo n.º 7
0
void HotCubeCube::paintCountdown (float timeLeft)
{
	String<16> time;
	time << (int)timeLeft << "." << Fixed((int)(timeLeft * 100) % 100, 2, true);

	writeText (time);
}
Exemplo n.º 8
0
void Image::clear(Color& c) {
    for (int i = 0; i < height; ++i) {
        for (int j = 0; j < width; ++j) {
            drawing[i][j].set_color(c);
            depth_buffer[i][j] = Fixed(11000.0);
        }
    }
}
Exemplo n.º 9
0
void Silo::NukeStrike()
{
    // Hit by nuke:
    // reduce remaining nukes

    Fixed lossFraction = Fixed(1) / 2;
    m_states[0]->m_numTimesPermitted = (m_states[0]->m_numTimesPermitted * lossFraction).IntValue();
    m_nukeSupply = m_states[0]->m_numTimesPermitted;
}
Exemplo n.º 10
0
void HotCubeCube::gameFinished (int totalIterations)
{
	clear();

	String<16> time;

	time << "TOTAL:" << Fixed(totalIterations, 2, true);

	buffer->bg1.text(vec(4,7), BlackFont, time);
}
Exemplo n.º 11
0
TString MillePedeTrees::AnyFreePar() const
{
  TString result("(");
  for (UInt_t iPar = 0; iPar < kNpar; ++iPar) { 
    result += Fixed(iPar, false);
    if (iPar != kNpar - 1) result += OrL();
    else result += ")";
  }

  return result;
}
void Player::HandleInput()
{
	if(TheGame::Instance()->KeyHeld(KEY_UP))
	{
		m_bMoving = true;
		m_velocity.m_y = Fixed(16); // 16
	}
	else if(TheGame::Instance()->KeyHeld(KEY_DOWN))
	{
		m_bMoving = true;
		m_velocity.m_y = Fixed(-16); // -16
	}
	else if(!TheGame::Instance()->KeyHeld(KEY_UP) || !TheGame::Instance()->KeyHeld(KEY_DOWN))
	{
		m_bMoving = false;
		m_velocity.m_y = Fixed(0);
	}

	if(TheGame::Instance()->KeyHeld(KEY_RIGHT))
	{
		m_bMoving = true;
		m_velocity.m_x = Fixed(-16);
	}
	else if(TheGame::Instance()->KeyHeld(KEY_LEFT))
	{
		m_bMoving = true;
		m_velocity.m_x = Fixed(16);
	}
	else if(!TheGame::Instance()->KeyHeld(KEY_RIGHT) || !TheGame::Instance()->KeyHeld(KEY_LEFT))
	{
		m_bMoving = false;
		m_velocity.m_x = Fixed(0);
	}
}
void AIPlayer::DoAI()
{
	switch (m_currentState)
	{
	case tennis::states_inplay :

		if(TheGame::Instance()->GetGameObject(2)->GetPosition().m_x > m_position.m_x)
		{
			m_velocity.m_x = Fixed(15);
		}
		else if(TheGame::Instance()->GetGameObject(2)->GetPosition().m_x < m_position.m_x)
		{
			m_velocity.m_x = Fixed(-15);
		}

		break;

	case tennis::states_p1serve:

		m_velocity.m_x = -(m_position.m_x - TheGame::Instance()->GetGameObject(2)->GetPosition().m_x);

		break;

	case tennis::states_p2serve:

		// AI player makes a random choice of where to serve the ball from
		choiceTimer += Fixed(1);

		if(!chosen)
		{
			chosenPos = rand() & (14 - 1); // faster than modulo
			chosen = true;
		}

		if(m_position.m_x < chosenPos || m_position.m_x > chosenPos )
		{
			m_velocity.m_x = -(m_position.m_x - (float)chosenPos); 
		}

		if(choiceTimer >= Fixed(50))
		{
			TheGame::Instance()->GetGameObject(2)->SetVelocity(Vec2f(Fixed(0), Fixed(10)));
			TheGame::Instance()->GetGameObject(2)->SetState(tennis::states_inplay);
			TheGame::Instance()->GetGameObject(0)->SetState(tennis::states_inplay);
			m_currentState = tennis::states_inplay;
			chosen = false;
			choiceTimer = Fixed(0);
		}
		break;

	case tennis::states_beforeplay:

		break;
	}
}
Exemplo n.º 14
0
static int FixedOrCommonCandidates(LKH::LKHAlg::Node * N,LKH::LKHAlg *Alg)
{
    int Count = 0;
    LKH::LKHAlg::Candidate *NN;

    if (N->FixedTo2)
        return 2;
    if (!N->FixedTo1 && Alg->MergeTourFiles < 2)
        return 0;
    for (NN = N->CandidateSet; NN->To; NN++)
        if ((Fixed(N, NN->To) || Alg->IsCommonEdge(N, NN->To)))
            Count++;
    return Count;
}
void SolveKCenterSubproblems()
{
    Node *N;
    GainType GlobalBestCost, OldGlobalBestCost;
    double EntryTime = GetTime();
    int CurrentSubproblem, Subproblems;

    AllocateStructures();
    ReadPenalties();

    /* Compute upper bound for the original problem */
    GlobalBestCost = 0;
    N = FirstNode;
    do {
        if (!Fixed(N, N->SubproblemSuc))
            GlobalBestCost += Distance(N, N->SubproblemSuc);
        N->Subproblem = 0;
    }
    while ((N = N->SubproblemSuc) != FirstNode);
    if (TraceLevel >= 1) {
        if (TraceLevel >= 2)
            printff("\n");
        printff("*** K-center partitioning *** [Cost = " GainFormat "]\n",
                GlobalBestCost);
    }

    Subproblems = (int) ceil((double) Dimension / SubproblemSize);
    KCenterClustering(Subproblems);
    for (CurrentSubproblem = 1;
         CurrentSubproblem <= Subproblems; CurrentSubproblem++) {
        OldGlobalBestCost = GlobalBestCost;
        SolveSubproblem(CurrentSubproblem, Subproblems, &GlobalBestCost);
        if (SubproblemsCompressed && GlobalBestCost == OldGlobalBestCost)
            SolveCompressedSubproblem(CurrentSubproblem, Subproblems,
                                      &GlobalBestCost);
    }
    printff("\nCost = " GainFormat, GlobalBestCost);
    if (Optimum != MINUS_INFINITY && Optimum != 0)
        printff(", Gap = %0.4f%%",
                100.0 * (GlobalBestCost - Optimum) / Optimum);
    printff(", Time = %0.2f sec. %s\n", fabs(GetTime() - EntryTime),
            GlobalBestCost < Optimum ? "<" : GlobalBestCost ==
            Optimum ? "=" : "");
    if (SubproblemBorders && Subproblems > 1)
        SolveSubproblemBorderProblems(Subproblems, &GlobalBestCost);
}
Exemplo n.º 16
0
int main( void ) {
    Fixed a;
    Fixed const b( 10 );
    Fixed const c( 42.42f );
    Fixed const d( b );

    a = Fixed( 1234.4321f );
    std::cout << "a is " << a << std::endl;
    std::cout << "b is " << b << std::endl;
    std::cout << "c is " << c << std::endl;
    std::cout << "d is " << d << std::endl;
    std::cout << "a is " << a.toInt() << " as integer" << std::endl;
    std::cout << "b is " << b.toInt() << " as integer" << std::endl;
    std::cout << "c is " << c.toInt() << " as integer" << std::endl;
    std::cout << "d is " << d.toInt() << " as integer" << std::endl;
    return (0);
}
Exemplo n.º 17
0
static LKH::LKHAlg::Node *RandomNode(LKH::LKHAlg * Alg)
{
    LKH::LKHAlg::Node *N;
    int Count;

    if (Alg->Dimension == Alg->DimensionSaved)
        N = &Alg->NodeSet[1 + Alg->Random() % Alg->Dimension];
    else {
        N = Alg->FirstNode;
        for (Count = Alg->Random() % Alg->Dimension; Count > 0; Count--)
            N = N->Suc;
    }
    Count = 0;
    while (((Fixed(N, N->Suc) || Alg->IsCommonEdge(N, N->Suc)) || N->V) && Count < Alg->Dimension) {
        N = N->Suc;
        Count++;
    }
    return Count < Alg->Dimension ? N : 0;
}
Exemplo n.º 18
0
Fixed * PBSynthMachine::tick_fixed_buffer()
{
  int i;
  SE->process(buffer_f,SAM);
  for(i=0;i<SAM;i++)
    {
      //Sint32 b=buffer_f[i]*1024;
      //buffer_fix[i]=b;
      buffer_fix[i]=Fixed(buffer_f[i]);
      if (trig_time_mode)
	{
	  if (trig_time_duration_sample<sample_num)
	    {
	      this->setI(NOTE_ON,0);
	      trig_time_mode=0;
	    }
	}
      sample_num++;
    }
  return buffer_fix;
}
Exemplo n.º 19
0
Fixed PBSynthMachine::tick_fixed()
{
  Sint16 s_in;
  Sint32 s_in32;
  Sint16 s_out;
  int    modulated_freq;
  int i;
  float buf_f;
  Fixed s_out_fix;

  if (index>=SAM | 
      index<0)
    index=0;

  if ( index==0 )
    {
      SE->process(buffer_f,SAM);
      for(i=0;i<SAM;i++)
       	{
	  buffer_fix[i]=Fixed(buffer_f[i]);
       	}
    }

  if (trig_time_mode)
    {
      if (trig_time_duration_sample<sample_num)
	{
	  this->setI(NOTE_ON,0);
	  trig_time_mode=0;
	}
    }

  s_out_fix=buffer_fix[index];

  index++;
  sample_num++;

  return s_out_fix;
}
Exemplo n.º 20
0
 LostSoul()
 {
     Radius = Fixed::FromInt(16);
     Height = Fixed::FromInt(56);
     Solid = true;
     Shootable = true;
     NoGravity = true;
     Floats = true;
     Health = 100;
     Speed = Fixed(8);
     Mass = 50;
     Damage = 3;
     PainChance = 256;
     ActiveSoundNum = sfx_dmact;
     AttackSoundNum = sfx_sklatk;
     PainSoundNum = sfx_dmpain;
     DeathSoundNum = sfx_firxpl;
     DefineState("Spawn",S_SKULL_STND);
     DefineState("See",S_SKULL_RUN1);
     DefineState("Missile",S_SKULL_ATK1);
     DefineState("Pain",S_SKULL_PAIN);
     DefineState("Death",S_SKULL_DIE1);
 }
void AIPlayer::Update(float gameSpeed)
{
	// save the current position
	Vec2f oldPos = m_position;

	switch (m_currentState)
	{
	case tennis::states_inplay :

		DoAI();

		if(m_velocity.m_x > Fixed(20))
		{
			m_velocity.m_x = Fixed(20);
		}
		else if(m_velocity.m_x < Fixed(-20))
		{
			m_velocity.m_x = Fixed(-20);
		}

		MeshObject::Update(gameSpeed);

		if(m_position.m_x >= Fixed(15) || m_position.m_x <= Fixed(-15))
		{
			m_position.m_x = oldPos.m_x;
		}
		else
		{
			m_position.m_x = m_position.m_x;
		}

		m_boundingBox->SetPos(Vec2f(m_position.m_x - 2.0f, m_position.m_y));

		break;

	case tennis::states_p1serve :

		m_position.m_y = Fixed(8);

		DoAI();

		if(m_velocity.m_x > Fixed(10))
		{
			m_velocity.m_x = Fixed(10);
		}
		else if(m_velocity.m_x < Fixed(-10))
		{
			m_velocity.m_x = Fixed(-10);
		}

		m_position.m_x += m_velocity.m_x * gameSpeed;

		if(m_position.m_x >= Fixed(14) || m_position.m_x <= Fixed(-14))
		{
			m_position.m_x = oldPos.m_x;
		}
		else
		{
			m_position.m_x = m_position.m_x;
		}

		m_boundingBox->SetPos(Vec2f(m_position.m_x - 2.0f, m_position.m_y));

		break;

	case tennis::states_p2serve :

		m_position.m_y = Fixed(8);

		DoAI();

		if(m_velocity.m_x > Fixed(10))
		{
			m_velocity.m_x = Fixed(10);
		}
		else if(m_velocity.m_x < Fixed(-10))
		{
			m_velocity.m_x = Fixed(-10);
		}

		m_position.m_x += m_velocity.m_x * gameSpeed;

		if(m_position.m_x >= Fixed(14) || m_position.m_x <= Fixed(-14))
		{
			m_position.m_x = oldPos.m_x;
		}
		else
		{
			m_position.m_x = m_position.m_x;
		}

		m_boundingBox->SetPos(Vec2f(m_position.m_x - 2.0f, m_position.m_y));

		break;

	case tennis::states_beforeplay:

		break;
	}
}
Exemplo n.º 22
0
int
SolveSubproblem(int CurrentSubproblem, int Subproblems,
                GainType * GlobalBestCost)
{
    Node *FirstNodeSaved = FirstNode, *N, *Next, *Last = 0;
    GainType OptimumSaved = Optimum, Cost, Improvement, GlobalCost;
    double LastTime, Time, ExcessSaved = Excess;
    int NewDimension = 0, OldDimension = 0, Number, i, InitialTourEdges = 0,
        AscentCandidatesSaved = AscentCandidates,
        InitialPeriodSaved = InitialPeriod, MaxTrialsSaved = MaxTrials;

    BestCost = PLUS_INFINITY;
    FirstNode = 0;
    N = FirstNodeSaved;
    do {
        if (N->Subproblem == CurrentSubproblem) {
            if (SubproblemsCompressed &&
                (((N->SubproblemPred == N->SubBestPred ||
                   FixedOrCommon(N, N->SubproblemPred) ||
                   (N->SubBestPred &&
                    (N->FixedTo1Saved == N->SubBestPred ||
                     N->FixedTo2Saved == N->SubBestPred))) &&
                  (N->SubproblemSuc == N->SubBestSuc ||
                   FixedOrCommon(N, N->SubproblemSuc) ||
                   (N->SubBestSuc &&
                    (N->FixedTo1Saved == N->SubBestSuc ||
                     N->FixedTo2Saved == N->SubBestSuc)))) ||
                 ((N->SubproblemPred == N->SubBestSuc ||
                   FixedOrCommon(N, N->SubproblemPred) ||
                   (N->SubBestSuc &&
                    (N->FixedTo1Saved == N->SubBestSuc ||
                     N->FixedTo2Saved == N->SubBestSuc))) &&
                  (N->SubproblemSuc == N->SubBestPred ||
                   FixedOrCommon(N, N->SubproblemSuc) ||
                   (N->SubBestPred &&
                    (N->FixedTo1Saved == N->SubBestPred ||
                     N->FixedTo2Saved == N->SubBestPred))))))
                N->Subproblem = -CurrentSubproblem;
            else {
                if (!FirstNode)
                    FirstNode = N;
                NewDimension++;
            }
            N->Head = N->Tail = 0;
            if (N->SubBestSuc)
                OldDimension++;
        }
        N->SubBestPred = N->SubBestSuc = 0;
        N->FixedTo1Saved = N->FixedTo1;
        N->FixedTo2Saved = N->FixedTo2;
    } while ((N = N->SubproblemSuc) != FirstNodeSaved);
    if ((Number = CurrentSubproblem % Subproblems) == 0)
        Number = Subproblems;
    if (NewDimension <= 3 || NewDimension == OldDimension) {
        if (TraceLevel >= 1 && NewDimension <= 3)
            printff
                ("\nSubproblem %d of %d: Dimension = %d (too small)\n",
                 Number, Subproblems, NewDimension);
        FirstNode = FirstNodeSaved;
        return 0;
    }
    if (AscentCandidates > NewDimension - 1)
        AscentCandidates = NewDimension - 1;
    if (InitialPeriod < 0) {
        InitialPeriod = NewDimension / 2;
        if (InitialPeriod < 100)
            InitialPeriod = 100;
    }
    if (Excess < 0)
        Excess = 1.0 / NewDimension;
    if (MaxTrials == -1)
        MaxTrials = NewDimension;
    N = FirstNode;
    do {
        Next = N->SubproblemSuc;
        if (N->Subproblem == CurrentSubproblem) {
            N->Pred = N->Suc = N;
            if (N != FirstNode)
                Follow(N, Last);
            Last = N;
        } else if (Next->Subproblem == CurrentSubproblem
                   && !Fixed(Last, Next)) {
            if (!Last->FixedTo1
                || Last->FixedTo1->Subproblem != CurrentSubproblem)
                Last->FixedTo1 = Next;
            else
                Last->FixedTo2 = Next;
            if (!Next->FixedTo1
                || Next->FixedTo1->Subproblem != CurrentSubproblem)
                Next->FixedTo1 = Last;
            else
                Next->FixedTo2 = Last;
            if (C == C_EXPLICIT) {
                if (Last->Id > Next->Id)
                    Last->C[Next->Id] = 0;
                else
                    Next->C[Last->Id] = 0;
            }
        }
    }
    while ((N = Next) != FirstNode);

    Dimension = NewDimension;
    AllocateSegments();
    InitializeStatistics();
    if (CacheSig)
        for (i = 0; i <= CacheMask; i++)
            CacheSig[i] = 0;
    OptimumSaved = Optimum;
    Optimum = 0;
    N = FirstNode;
    do {
        if (N->SubproblemSuc == N->InitialSuc ||
            N->SubproblemPred == N->InitialSuc)
            InitialTourEdges++;
        if (!Fixed(N, N->Suc))
            Optimum += Distance(N, N->Suc);
        if (N->FixedTo1 && N->Subproblem != N->FixedTo1->Subproblem)
            eprintf("Illegal fixed edge (%d,%d)", N->Id, N->FixedTo1->Id);
        if (N->FixedTo2 && N->Subproblem != N->FixedTo2->Subproblem)
            eprintf("Illegal fixed edge (%d,%d)", N->Id, N->FixedTo2->Id);
    }
    while ((N = N->Suc) != FirstNode);
    if (TraceLevel >= 1)
        printff
            ("\nSubproblem %d of %d: Dimension = %d, Upper bound = "
             GainFormat "\n", Number, Subproblems, Dimension, Optimum);
    FreeCandidateSets();
    CreateCandidateSet();

    for (Run = 1; Run <= Runs; Run++) {
        LastTime = GetTime();
        Cost = Norm != 0 ? FindTour() : Optimum;
        /* Merge with subproblem tour */
        Last = 0;
        N = FirstNode;
        do {
            if (N->Subproblem == CurrentSubproblem) {
                if (Last)
                    Last->Next = N;
                Last = N;
            }
        }
        while ((N = N->SubproblemSuc) != FirstNode);
        Last->Next = FirstNode;
        Cost = MergeWithTour();
        if (MaxPopulationSize > 1) {
            /* Genetic algorithm */
            for (i = 0; i < PopulationSize; i++)
                Cost = MergeTourWithIndividual(i);
            if (!HasFitness(Cost)) {
                if (PopulationSize < MaxPopulationSize) {
                    AddToPopulation(Cost);
                    if (TraceLevel >= 1)
                        PrintPopulation();
                } else if (Cost < Fitness[PopulationSize - 1]) {
                    ReplaceIndividualWithTour(PopulationSize - 1, Cost);
                    if (TraceLevel >= 1)
                        PrintPopulation();
                }
            }
        }
        if (Cost < BestCost) {
            N = FirstNode;
            do {
                N->SubBestPred = N->Pred;
                N->SubBestSuc = N->Suc;
            } while ((N = N->Suc) != FirstNode);
            BestCost = Cost;
        }
        if (Cost < Optimum || (Cost != Optimum && OutputTourFileName)) {
            Improvement = Optimum - Cost;
            if (Improvement > 0) {
                BestCost = GlobalCost = *GlobalBestCost -= Improvement;
                Optimum = Cost;
            } else
                GlobalCost = *GlobalBestCost - Improvement;
            N = FirstNode;
            do
                N->Mark = 0;
            while ((N = N->SubproblemSuc) != FirstNode);
            do {
                N->Mark = N;
                if (!N->SubproblemSuc->Mark &&
                    (N->Subproblem != CurrentSubproblem ||
                     N->SubproblemSuc->Subproblem != CurrentSubproblem))
                    N->BestSuc = N->SubproblemSuc;
                else if (!N->SubproblemPred->Mark &&
                         (N->Subproblem != CurrentSubproblem ||
                          N->SubproblemPred->Subproblem !=
                          CurrentSubproblem))
                    N->BestSuc = N->SubproblemPred;
                else if (!N->Suc->Mark)
                    N->BestSuc = N->Suc;
                else if (!N->Pred->Mark)
                    N->BestSuc = N->Pred;
                else
                    N->BestSuc = FirstNode;
            }
            while ((N = N->BestSuc) != FirstNode);
            Dimension = DimensionSaved;
            i = 0;
            do {
                if (ProblemType != ATSP)
                    BetterTour[++i] = N->Id;
                else if (N->Id <= Dimension / 2) {
                    i++;
                    if (N->BestSuc->Id != N->Id + Dimension / 2)
                        BetterTour[i] = N->Id;
                    else
                        BetterTour[Dimension / 2 - i + 1] = N->Id;
                }
            }
            while ((N = N->BestSuc) != FirstNode);
            BetterTour[0] =
                BetterTour[ProblemType !=
                           ATSP ? Dimension : Dimension / 2];
            WriteTour(OutputTourFileName, BetterTour, GlobalCost);
            if (Improvement > 0) {
                do
                    if (N->Subproblem != CurrentSubproblem)
                        break;
                while ((N = N->SubproblemPred) != FirstNode);
                if (N->SubproblemSuc == N->BestSuc) {
                    N = FirstNode;
                    do {
                        N->BestSuc->SubproblemPred = N;
                        N = N->SubproblemSuc = N->BestSuc;
                    }
                    while (N != FirstNode);
                } else {
                    N = FirstNode;
                    do
                        (N->SubproblemPred = N->BestSuc)->SubproblemSuc =
                            N;
                    while ((N = N->BestSuc) != FirstNode);
                }
                RecordBestTour();
                WriteTour(TourFileName, BestTour, GlobalCost);
            }
            Dimension = NewDimension;
            if (TraceLevel >= 1) {
                printff("*** %d: Cost = " GainFormat, Number, GlobalCost);
                if (OptimumSaved != MINUS_INFINITY && OptimumSaved != 0)
                    printff(", Gap = %04f%%",
                            100.0 * (GlobalCost -
                                     OptimumSaved) / OptimumSaved);
                printff(", Time = %0.2f sec. %s\n",
                        fabs(GetTime() - LastTime),
                        GlobalCost < OptimumSaved ? "<" : GlobalCost ==
                        OptimumSaved ? "=" : "");
            }
        }

        Time = fabs(GetTime() - LastTime);
        UpdateStatistics(Cost, Time);
        if (TraceLevel >= 1 && Cost != PLUS_INFINITY)
            printff("Run %d: Cost = " GainFormat ", Time = %0.2f sec.\n\n",
                    Run, Cost, Time);
        if (PopulationSize >= 2 &&
            (PopulationSize == MaxPopulationSize
             || Run >= 2 * MaxPopulationSize) && Run < Runs) {
            Node *N;
            int Parent1, Parent2;
            Parent1 = LinearSelection(PopulationSize, 1.25);
            do
                Parent2 = LinearSelection(PopulationSize, 1.25);
            while (Parent1 == Parent2);
            ApplyCrossover(Parent1, Parent2);
            N = FirstNode;
            do {
                int d = C(N, N->Suc);
                AddCandidate(N, N->Suc, d, INT_MAX);
                AddCandidate(N->Suc, N, d, INT_MAX);
                N = N->InitialSuc = N->Suc;
            }
            while (N != FirstNode);
        }
        SRandom(++Seed);
        if (Norm == 0)
            break;
    }

    if (TraceLevel >= 1)
        PrintStatistics();

    if (C == C_EXPLICIT) {
        N = FirstNode;
        do {
            for (i = 1; i < N->Id; i++) {
                N->C[i] -= N->Pi + NodeSet[i].Pi;
                N->C[i] /= Precision;
            }
            if (N->FixedTo1 && N->FixedTo1 != N->FixedTo1Saved) {
                if (N->Id > N->FixedTo1->Id)
                    N->C[N->FixedTo1->Id] = Distance(N, N->FixedTo1);
                else
                    N->FixedTo1->C[N->Id] = Distance(N, N->FixedTo1);
            }
            if (N->FixedTo2 && N->FixedTo2 != N->FixedTo2Saved) {
                if (N->Id > N->FixedTo2->Id)
                    N->C[N->FixedTo2->Id] = Distance(N, N->FixedTo2);
                else
                    N->FixedTo2->C[N->Id] = Distance(N, N->FixedTo2);
            }
        }
        while ((N = N->Suc) != FirstNode);
    }

    FreeSegments();
    FreeCandidateSets();
    FreePopulation();
    if (InitialTourEdges == Dimension) {
        do
            N->InitialSuc = N->SubproblemSuc;
        while ((N = N->SubproblemSuc) != FirstNode);
    } else {
        do
            N->InitialSuc = 0;
        while ((N = N->SubproblemSuc) != FirstNode);
    }
    Dimension = ProblemType != ATSP ? DimensionSaved : 2 * DimensionSaved;
    N = FirstNode = FirstNodeSaved;
    do {
        N->Suc = N->BestSuc = N->SubproblemSuc;
        N->Suc->Pred = N;
        Next = N->FixedTo1;
        N->FixedTo1 = N->FixedTo1Saved;
        N->FixedTo1Saved = Next;
        Next = N->FixedTo2;
        N->FixedTo2 = N->FixedTo2Saved;
        N->FixedTo2Saved = Next;
    }
    while ((N = N->Suc) != FirstNode);
    Optimum = OptimumSaved;
    Excess = ExcessSaved;
    AscentCandidates = AscentCandidatesSaved;
    InitialPeriod = InitialPeriodSaved;
    MaxTrials = MaxTrialsSaved;
    return 1;
}
Exemplo n.º 23
0
void init(){
	FreeStructures();
	FirstNode = 0;
	WeightType = EXPLICIT;

	WeightFormat = FULL_MATRIX;
	ProblemType = ATSP;

	CoordType = NO_COORDS;
//	Name = "Unnamed";
	Type = EdgeWeightType = EdgeWeightFormat = 0;
	EdgeDataFormat = NodeCoordType = DisplayDataType = 0;
	Distance = 0;
	C = 0;
	c = 0;


	Distance = Distance_EXPLICIT;

	DimensionSaved = Dimension = TSP_N;
	init_graph();




	Swaps = 0;

	/* Adjust parameters */
	if (Seed == 0)
		Seed = (unsigned)time(0);
	if (Precision == 0)
		Precision = 100;
	if (InitialStepSize == 0)
		InitialStepSize = 1;
	if (MaxSwaps < 0)
		MaxSwaps = Dimension;
	if (KickType > Dimension / 2)
		KickType = Dimension / 2;

	if (Runs == 0)
		Runs = 10;

	if (MaxCandidates > Dimension - 1)
		MaxCandidates = Dimension - 1;
	if (ExtraCandidates > Dimension - 1)
		ExtraCandidates = Dimension - 1;
	if (SubproblemSize >= Dimension)
		SubproblemSize = Dimension;
	else if (SubproblemSize == 0) {
		if (AscentCandidates > Dimension - 1)
			AscentCandidates = Dimension - 1;
		if (InitialPeriod < 0) {
			InitialPeriod = Dimension / 2;
			if (InitialPeriod < 100)
				InitialPeriod = 100;
		}
		if (Excess < 0)
			Excess = 1.0 / Dimension;
		if (MaxTrials == -1)
			MaxTrials = Dimension;
		MakeHeap(Dimension);
	}

	if (CostMatrix == 0 && Dimension <= MaxMatrixDimension && Distance != 0
		&& Distance != Distance_1 && Distance != Distance_ATSP) {
		Node *Ni, *Nj;
		assert(CostMatrix =
			(int *)calloc((size_t)Dimension * (Dimension - 1) / 2,
			sizeof(int)));
		Ni = FirstNode->Suc;
		do {
			Ni->C =
				&CostMatrix[(size_t)(Ni->Id - 1) * (Ni->Id - 2) / 2] - 1;
			if (ProblemType != HPP || Ni->Id < Dimension)
			for (Nj = FirstNode; Nj != Ni; Nj = Nj->Suc)
				Ni->C[Nj->Id] = Fixed(Ni, Nj) ? 0 : Distance(Ni, Nj);
			else
			for (Nj = FirstNode; Nj != Ni; Nj = Nj->Suc)
				Ni->C[Nj->Id] = 0;
		} while ((Ni = Ni->Suc) != FirstNode);
		WeightType = EXPLICIT;
		c = 0;
	}


	if (Precision > 1 && (WeightType == EXPLICIT || ProblemType == ATSP)) {
		int j, n = ProblemType == ATSP ? Dimension / 2 : Dimension;
		for (int i = 2; i <= n; i++) {
			Node *N = &NodeSet[i];
			for (j = 1; j < i; j++)
			if (N->C[j] * Precision / Precision != N->C[j])
			{
				printf("PRECISION (= %d) is too large", Precision);
				system("pause");
			}

		}
	}



	C = WeightType == EXPLICIT ? C_EXPLICIT : C_FUNCTION;
	D = WeightType == EXPLICIT ? D_EXPLICIT : D_FUNCTION;
	if (SubsequentMoveType == 0)
		SubsequentMoveType = MoveType;
	int K = MoveType >= SubsequentMoveType
		|| !SubsequentPatching ? MoveType : SubsequentMoveType;
	if (PatchingC > K)
		PatchingC = K;
	if (PatchingA > 1 && PatchingA >= PatchingC)
		PatchingA = PatchingC > 2 ? PatchingC - 1 : 1;
	if (NonsequentialMoveType == -1 ||
		NonsequentialMoveType > K + PatchingC + PatchingA - 1)
		NonsequentialMoveType = K + PatchingC + PatchingA - 1;
	if (PatchingC >= 1 && NonsequentialMoveType >= 4) {
		BestMove = BestSubsequentMove = BestKOptMove;
		if (!SubsequentPatching && SubsequentMoveType <= 5) {
			MoveFunction BestOptMove[] =
			{ 0, 0, Best2OptMove, Best3OptMove,
			Best4OptMove, Best5OptMove
			};
			BestSubsequentMove = BestOptMove[SubsequentMoveType];
		}
	}
	else {
		MoveFunction BestOptMove[] = { 0, 0, Best2OptMove, Best3OptMove,
			Best4OptMove, Best5OptMove
		};
		BestMove = MoveType <= 5 ? BestOptMove[MoveType] : BestKOptMove;
		BestSubsequentMove = SubsequentMoveType <= 5 ?
			BestOptMove[SubsequentMoveType] : BestKOptMove;
	}
	if (ProblemType == HCP || ProblemType == HPP)
		MaxCandidates = 0;
	//if (TraceLevel >= 1) {
	//	printff("done\n");
	//	PrintParameters();
	//}





}
Exemplo n.º 24
0
GainType SFCTour(int CurveType)
{
    double XMin, XMax, YMin, YMax;
    Node *N, **Perm;
    int i;
    IndexFunction Index;
    GainType Cost;
    double EntryTime = GetTime();

    if (CurveType == SIERPINSKI) {
        if (TraceLevel >= 1)
            printff("Sierpinski = ");
        Index = SierpinskiIndex;
    } else {
        if (TraceLevel >= 1)
            printff("Moore = ");
        Index = MooreIndex;
    }
    N = FirstNode;
    XMin = XMax = N->X;
    YMin = YMax = N->Y;
    N->V = 0;
    while ((N = N->Suc) != FirstNode) {
        if (N->X < XMin)
            XMin = N->X;
        else if (N->X > XMax)
            XMax = N->X;
        if (N->Y < YMin)
            YMin = N->Y;
        else if (N->Y > YMax)
            YMax = N->Y;
    }
    if (XMax == XMin)
        XMax = XMin + 1;
    if (YMax == YMin)
        YMax = YMin + 1;

    assert(Perm = (Node **) malloc(Dimension * sizeof(Node *)));
    for (i = 0, N = FirstNode; i < Dimension; i++, N = N->Suc)
        (Perm[i] = N)->V =
            Index((N->X - XMin) / (XMax - XMin),
                  (N->Y - YMin) / (YMax - YMin));
    qsort(Perm, Dimension, sizeof(Node *), compare);
    for (i = 1; i < Dimension; i++)
        Follow(Perm[i], Perm[i - 1]);
    free(Perm);

    /* Assure that all fixed or common edges belong to the tour */
    N = FirstNode;
    do {
        N->LastV = 1;
        if (!FixedOrCommon(N, N->Suc) && N->CandidateSet) {
            Candidate *NN;
            for (NN = N->CandidateSet; NN->To; NN++) {
                if (!NN->To->LastV && FixedOrCommon(N, NN->To)) {
                    Follow(NN->To, N);
                    break;
                }
            }
        }
    } while ((N = N->Suc) != FirstNode);

    Cost = 0;
    N = FirstNode;
    do
        if (!Fixed(N, N->Suc))
            Cost += Distance(N, N->Suc);
    while ((N = N->Suc) != FirstNode);
    if (TraceLevel >= 1) {
        printff(GainFormat, Cost);
        if (Optimum != MINUS_INFINITY && Optimum != 0)
            printff(", Gap = %0.1f%%", 100.0 * (Cost - Optimum) / Optimum);
        printff(", Time = %0.2f sec.\n", fabs(GetTime() - EntryTime));
    }
    return Cost;
}
Exemplo n.º 25
0
int D_FUNCTION(Node * Na, Node * Nb)
{
    return (Fixed(Na, Nb) ? 0 : Distance(Na, Nb) * Precision) + Na->Pi +
        Nb->Pi;
}
Exemplo n.º 26
0
void ChooseInitialTour()
{
    Node *N, *NextN, *FirstAlternative, *Last;
    Candidate *NN;
    int Alternatives, Count, i;

    if (KickType > 0 && Kicks > 0 && Trial > 1) {
        for (Last = FirstNode; (N = Last->BestSuc) != FirstNode; Last = N)
            Follow(N, Last);
        for (i = 1; i <= Kicks; i++)
            KSwapKick(KickType);
        return;
    }
    if (Trial == 1 && (!FirstNode->InitialSuc || InitialTourFraction < 1)) {
        if (InitialTourAlgorithm == BORUVKA ||
            InitialTourAlgorithm == GREEDY ||
            InitialTourAlgorithm == MOORE ||
            InitialTourAlgorithm == NEAREST_NEIGHBOR ||
            InitialTourAlgorithm == QUICK_BORUVKA ||
            InitialTourAlgorithm == SIERPINSKI) {
            GainType Cost = InitialTourAlgorithm == MOORE ||
                InitialTourAlgorithm == SIERPINSKI ?
                SFCTour(InitialTourAlgorithm) : GreedyTour();
            if (MaxTrials == 0) {
                BetterCost = Cost;
                RecordBetterTour();
            }
            if (!FirstNode->InitialSuc)
                return;
        }
    }

Start:
    /* Mark all nodes as "not chosen" by setting their V field to zero */
    N = FirstNode;
    do
        N->V = 0;
    while ((N = N->Suc) != FirstNode);
    Count = 0;

    /* Choose FirstNode without two incident fixed or common candidate edges */
    do {
        if (FixedOrCommonCandidates(N) < 2)
            break;
    }
    while ((N = N->Suc) != FirstNode);
    if (ProblemType == ATSP && N->Id <= DimensionSaved)
        N += DimensionSaved;
    FirstNode = N;

    /* Move nodes with two incident fixed or common candidate edges in 
       front of FirstNode */
    for (Last = FirstNode->Pred; N != Last; N = NextN) {
        NextN = N->Suc;
        if (FixedOrCommonCandidates(N) == 2)
            Follow(N, Last);
    }

    /* Mark FirstNode as chosen */
    FirstNode->V = 1;
    N = FirstNode;

    /* Loop as long as not all nodes have been chosen */
    while (N->Suc != FirstNode) {
        FirstAlternative = 0;
        Alternatives = 0;
        Count++;

        /* Case A */
        for (NN = N->CandidateSet; (NextN = NN->To); NN++) {
            if (!NextN->V && Fixed(N, NextN)) {
                Alternatives++;
                NextN->Next = FirstAlternative;
                FirstAlternative = NextN;
            }
        }
        if (Alternatives == 0 && MergeTourFiles > 1) {
            for (NN = N->CandidateSet; (NextN = NN->To); NN++) {
                if (!NextN->V && IsCommonEdge(N, NextN)) {
                    Alternatives++;
                    NextN->Next = FirstAlternative;
                    FirstAlternative = NextN;
                }
            }
        }
        if (Alternatives == 0 && FirstNode->InitialSuc && Trial == 1 &&
            Count <= InitialTourFraction * Dimension) {
            /* Case B */
            for (NN = N->CandidateSet; (NextN = NN->To); NN++) {
                if (!NextN->V && InInitialTour(N, NextN)) {
                    Alternatives++;
                    NextN->Next = FirstAlternative;
                    FirstAlternative = NextN;
                }
            }
        }
        if (Alternatives == 0 && Trial > 1 &&
            ProblemType != HCP && ProblemType != HPP) {
            /* Case C */
            for (NN = N->CandidateSet; (NextN = NN->To); NN++) {
                if (!NextN->V && FixedOrCommonCandidates(NextN) < 2 &&
                    NN->Alpha == 0 && (InBestTour(N, NextN) ||
                                       InNextBestTour(N, NextN))) {
                    Alternatives++;
                    NextN->Next = FirstAlternative;
                    FirstAlternative = NextN;
                }
            }
        }
        if (Alternatives == 0) {
            /* Case D */
            for (NN = N->CandidateSet; (NextN = NN->To); NN++) {
                if (!NextN->V && FixedOrCommonCandidates(NextN) < 2) {
                    Alternatives++;
                    NextN->Next = FirstAlternative;
                    FirstAlternative = NextN;
                }
            }
        }
        if (Alternatives == 0) {
            /* Case E (actually not really a random choice) */
            NextN = N->Suc;
            while ((FixedOrCommonCandidates(NextN) == 2 || Forbidden(N, NextN))
                   && NextN->Suc != FirstNode)
                NextN = NextN->Suc;
            if (FixedOrCommonCandidates(NextN) == 2 || Forbidden(N, NextN)) {
                FirstNode = FirstNode->Suc;
                goto Start;
            }
        } else {
            NextN = FirstAlternative;
            if (Alternatives > 1) {
                /* Select NextN at random among the alternatives */
                i = Random() % Alternatives;
                while (i--)
                    NextN = NextN->Next;
            }
        }
        /* Include NextN as the successor of N */
        Follow(NextN, N);
        N = NextN;
        N->V = 1;
    }
    if (Forbidden(N, N->Suc)) {
        FirstNode = FirstNode->Suc;
        goto Start;
    }
    if (MaxTrials == 0) {
        GainType Cost = 0;
        N = FirstNode;
        do
            Cost += C(N, N->Suc) - N->Pi - N->Suc->Pi;
        while ((N = N->Suc) != FirstNode);
        Cost /= Precision;
        if (Cost < BetterCost) {
            BetterCost = Cost;
            RecordBetterTour();
        }
    }
}
Exemplo n.º 27
0
static GainType BestKOptMoveRec(int k, GainType G0,LKH::LKHAlg *Alg)
{
    LKH::LKHAlg::Candidate *Nt2;
    LKH::LKHAlg::Node *t1, *t2, *t3, *t4;
    GainType G1, G2, G3, Gain;
    int X4, i;
    int Breadth2 = 0;

    t1 = (*t.get())[1];
    t2 = (*t.get())[i = 2 * k - 2];
    (*incl.get())[(*incl.get())[i] = i + 1] = i;
    (*incl.get())[(*incl.get())[1] = i + 2] = 1;
    /* Choose (t2,t3) as a candidate edge emanating from t2 */
    for (Nt2 = t2->CandidateSet; (t3 = Nt2->To); Nt2++) {
        if (t3 == t2->Pred || t3 == t2->Suc ||
            ((G1 = G0 - Nt2->Cost) <= 0 && Alg->GainCriterionUsed &&
             Alg->ProblemType != LKH::HCP && Alg->ProblemType != LKH::HPP)
            || Added(t2, t3))
            continue;
        if (++Breadth2 > Alg->MaxBreadth)
            break;
        MarkAdded(t2, t3);
        (*t.get())[2 * k - 1] = t3;
        (*G.get())[2 * k - 2] = G1 + t3->Pi;
        /* Choose t4 as one of t3's two neighbors on the tour */
        for (X4 = 1; X4 <= 2; X4++) {
            t4 = X4 == 1 ? (Alg->Reversed == (t3)->Parent->Reversed ? (t3)->Pred : (t3)->Suc) : (Alg->Reversed == (t3)->Parent->Reversed ? (t3)->Suc : (t3)->Pred);
            if ((Fixed(t3, t4) || Alg->IsCommonEdge(t3, t4)) || Deleted(t3, t4))
                continue;
            (*t.get())[2 * k] = t4;
            G2 = G1 + (Alg->*(Alg->C))(t3, t4);
            G3 = MINUS_INFINITY;
            if (t4 != t1 && !Alg->Forbidden(t4, t1) && !Added(t4, t1) &&
				(!Alg->c || G2 - (Alg->*(Alg->c))(t4, t1) > 0) &&
                (G3 = G2 - (Alg->*(Alg->C))(t4, t1)) > 0 && FeasibleKOptMove(k)) {
                UnmarkAdded(t2, t3);
                Alg->MakeKOptMove(k);
                return G3;
            }
            if (Alg->Backtracking && !Alg->Excludable(t3, t4))
                continue;
            MarkDeleted(t3, t4);
            (*G.get())[2 * k - 1] = G2 - t4->Pi;
            if (k < *K) {
				if ((Gain = BestKOptMoveRec(k + 1, G2,Alg)) > 0) {
                    UnmarkAdded(t2, t3);
                    UnmarkDeleted(t3, t4);
                    return Gain;
                }
                (*incl.get())[(*incl.get())[1] = 2 * k] = 1;
            }
            if (t4 != t1 && !Alg->Forbidden(t4, t1) &&
                k + 1 < Alg->NonsequentialMoveType &&
                Alg->PatchingC >= 2 && Alg->PatchingA >= 1 &&
                (Alg->Swaps == 0 || Alg->SubsequentPatching)) {
                if (G3 == MINUS_INFINITY)
                    G3 = G2 - (Alg->*(Alg->C))(t4, t1);
                if ((Alg->PatchingCRestricted ? G3 > 0 && Alg->IsCandidate(t4, t1) :
                     Alg->PatchingCExtended ? G3 > 0
                     || Alg->IsCandidate(t4, t1) : G3 > 0)
                    && (Gain = Alg->PatchCycles(k, G3)) > 0) {
                    UnmarkAdded(t2, t3);
                    UnmarkDeleted(t3, t4);
                    return Gain;
                }
            }
            UnmarkDeleted(t3, t4);
            if (k == *K && t4 != t1 && t3 != t1 && G3 <= 0 &&
                !Added(t4, t1) &&
                (!Alg->GainCriterionUsed || G2 - Alg->Precision >= t4->Cost)) {
                if (!Alg->Backtracking || Alg->Swaps > 0) {
                    if ((G2 > *BestG2 ||
                         (G2 == *BestG2 && !Near(t3, t4) &&
                          Near((*T.get())[2 * *K - 1], (*T.get())[2 * *K]))) &&
                        Alg->Swaps < Alg->MaxSwaps &&
                        Alg->Excludable(t3, t4) && !InInputTour(t3, t4)) {
                        if (Alg->RestrictedSearch && *K > 2 &&
                            Alg->ProblemType != LKH::HCP && Alg->ProblemType != LKH::HPP) {
                            /* Ignore the move if the gain does not vary */
                            (*G.get())[0] = (*G.get())[2 * *K - 2];
                            (*G.get())[1] = (*G.get())[2 * *K - 1];
                            for (i = 2 * *K - 3; i >= 2; i--)
                                if ((*G.get())[i] != (*G.get())[i % 2])
                                    break;
                            if (i < 2)
                                continue;
                        }
                        if (FeasibleKOptMove(*K)) {
                            *BestG2 = G2;
                            memcpy(T.get() + 1, t.get() + 1, 2 * *K * sizeof(LKH::LKHAlg::Node *));
                        }
                    }
                } else if (Alg->MaxSwaps > 0 && FeasibleKOptMove(*K)) {
					LKH::LKHAlg::Node *SUCt1 = (Alg->Reversed == (t1)->Parent->Reversed ? (t1)->Suc : (t1)->Pred);
                    Alg->MakeKOptMove(*K);
                    for (i = 1; i < 2 * k; i += 2) {
                        Alg->Exclude((*t.get())[i], (*t.get())[i + 1]);
                        UnmarkDeleted((*t.get())[i], (*t.get())[i + 1]);
                    }
                    for (i = 2; i < 2 * k; i += 2)
                        UnmarkAdded((*t.get())[i], (*t.get())[i + 1]);
                    memcpy(tSaved.get() + 1, t.get() + 1, 2 * k * sizeof(LKH::LKHAlg::Node *));
                    while ((t4 = (Alg->*(Alg->BestSubsequentMove))(t1, t4, &G2, &Gain)));
                    if (Gain > 0) {
                        UnmarkAdded(t2, t3);
                        return Gain;
                    }
                    Alg->RestoreTour();
                    *K = k;
                    memcpy(t.get() + 1, tSaved.get() + 1, 2 * *K * sizeof(LKH::LKHAlg::Node *));
                    for (i = 1; i < 2 * *K - 2; i += 2)
                        MarkDeleted((*t.get())[i], (*t.get())[i + 1]);
                    for (i = 2; i < 2 * *K; i += 2)
                        MarkAdded((*t.get())[i], (*t.get())[i + 1]);
                    for (i = 2; i < 2 * *K; i += 2)
                        (*incl.get())[(*incl.get())[i] = i + 1] = i;
                    (*incl.get())[(*incl.get())[1] = 2 * *K] = 1;
                    if (SUCt1 != (Alg->Reversed == (t1)->Parent->Reversed ? (t1)->Suc : (t1)->Pred))
                        Alg->Reversed ^= 1;
                    (*T.get())[2 * *K] = 0;
                }
            }
        }
        UnmarkAdded(t2, t3);
        if (t3 == t1)
            continue;
        /* Try to delete an added edge, (_,t3) or (t3,_) */
        for (i = 2 * k - 4; i >= 2; i--) {
            if (t3 == (*t.get())[i]) {
                t4 = (*t.get())[i ^ 1];
                if (t4 == t1 || Alg->Forbidden(t4, t1) || (Fixed(t3, t4) || Alg->IsCommonEdge(t3, t4)) ||
                    Added(t4, t1))
                    continue;
                G2 = G1 + (Alg->*(Alg->C))(t3, t4);
                if ((!Alg->c || G2 - (Alg->*(Alg->c))(t4, t1) > 0)
                    && (Gain = G2 - (Alg->*(Alg->C))(t4, t1)) > 0) {
                    (*incl.get())[(*incl.get())[i ^ 1] = 1] = i ^ 1;
                    (*incl.get())[(*incl.get())[i] = 2 * k - 2] = i;
                    if (FeasibleKOptMove(k - 1)) {
                        Alg->MakeKOptMove(k - 1);
                        return Gain;
                    }
                    (*incl.get())[(*incl.get())[i ^ 1] = i] = i ^ 1;
                }
            }
        }
        (*incl.get())[1] = 2 * k;
        (*incl.get())[2 * k - 2] = 2 * k - 1;
    }
    return 0;
}
Exemplo n.º 28
0
void SolveKarpSubproblems()
{
    Node *N;
    int i;
    double EntryTime = GetTime();

    AllocateStructures();
    ReadPenalties();
    /* Compute upper bound for the original problem */
    GlobalBestCost = 0;
    N = FirstNode;
    do {
        if (!Fixed(N, N->SubproblemSuc))
            GlobalBestCost += Distance(N, N->SubproblemSuc);
        N->Subproblem = 0;
    }
    while ((N = N->BestSuc = N->SubproblemSuc) != FirstNode);
    if (TraceLevel >= 1) {
        if (TraceLevel >= 2)
            printff("\n");
        printff("*** Karp partitioning *** [Cost = " GainFormat "]\n",
                GlobalBestCost);
    }
    if (WeightType == GEO || WeightType == GEOM ||
        WeightType == GEO_MEEUS || WeightType == GEOM_MEEUS) {
        N = FirstNode;
        do {
            N->Xc = N->X;
            N->Yc = N->Y;
            N->Zc = N->Z;
            if (WeightType == GEO || WeightType == GEO_MEEUS)
                GEO2XYZ(N->Xc, N->Yc, &N->X, &N->Y, &N->Z);
            else
                GEOM2XYZ(N->Xc, N->Yc, &N->X, &N->Y, &N->Z);
        } while ((N = N->SubproblemSuc) != FirstNode);
        CoordType = THREED_COORDS;
    }
    KDTree = BuildKDTree();
    if (WeightType == GEO || WeightType == GEOM ||
        WeightType == GEO_MEEUS || WeightType == GEOM_MEEUS) {
        N = FirstNode;
        do {
            N->X = N->Xc;
            N->Y = N->Yc;
            N->Z = N->Zc;
        } while ((N = N->SubproblemSuc) != FirstNode);
        CoordType = TWOD_COORDS;
    }

    CurrentSubproblem = 0;
    Subproblems = 1;
    for (i = Dimension - 1; i > SubproblemSize; i /= 2)
        Subproblems *= 2;
    RestrictedSearchSaved = RestrictedSearch;
    KarpPartition(0, Dimension - 1, 0);
    free(KDTree);
    printff("\nCost = " GainFormat, GlobalBestCost);
    if (Optimum != MINUS_INFINITY && Optimum != 0)
        printff(", Gap = %0.3f%%",
                100.0 * (GlobalBestCost - Optimum) / Optimum);
    printff(", Time = %0.1f sec. %s\n", fabs(GetTime() - EntryTime),
            GlobalBestCost < Optimum ? "<" : GlobalBestCost ==
            Optimum ? "=" : "");
    if (SubproblemBorders && Subproblems > 1)
        SolveSubproblemBorderProblems(Subproblems);
}
Exemplo n.º 29
0
static unsigned int AdcCountsToBatteryVoltage(unsigned int Counts)
{
	return (int)(Fixed((int)Counts) * FIXED_CONVERSION_FACTOR_BATTERY);
}
Exemplo n.º 30
0
static unsigned int AdcCountsToVoltage(unsigned int Counts)
{
	return (int)(Fixed((int)Counts) * FIXED_CONVERSION_FACTOR);
}