约瑟夫环问题,自认为效率还可以;

来源:互联网 发布:日记本软件排名榜 编辑:程序博客网 时间:2024/05/17 09:11

#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;

struct ListNode
{
 int id;
 int data;
 int cur;
};

static int count = 7;
static int pos = 0;
void yue(ListNode *plist, int length, int m)
{
 //int pos = 0;
 while(count >= 1)
 {
  
  pos = (m%length + pos -1 + (length - count) * (m)/length + length) % length;
  
  while(plist[pos].id == -1)
  {
   pos = plist[pos].cur;
  }

  int next = plist[pos].cur;
  int temp = pos;
  

  while(plist[temp].cur!=pos)
  {
   temp = plist[temp].cur;
  }


  plist[temp].cur = next;
  cout << plist[pos].id;
  plist[pos].id = -1;
  count --;

  m = plist[pos].data;
  pos = plist[next].id;
   
  yue(plist, length, m);

 }
}

void test(int a[], int length, int m)
{
 while(length>=1)
 {
  int pos = ((m%length - 1) + length ) % length;

 }
}


int _tmain(int argc, _TCHAR* argv[])
{
 
 int array[] = {3, 1, 7, 2, 4, 8, 4};
 ListNode myarray[7];
 for(int i = 0; i < 7; i++)
 {
  myarray[i].id = i;
  myarray[i].data = array[i];
  myarray[i].cur = (i+1)%7;
 }
 yue(myarray, 7, 20);
 return 0;
}