質問 :候補者を採用する会社が、候補者を輪になって座らせます。彼らは 1 人おきに候補を選び、1 人だけが残るまで、彼はサークルを離れます (したがって、サークルは小さくなり続けます)。5人だとこんな感じになります(-_-;)
1 2 3 4 5
1 3 4 5 (2 is selected)
1 3 5 (4 is selected)
3 5 (1 is selected)
3 (3 is left, does'nt get the job!)
賢すぎるジョンは、この意地悪な会社の一員になりたくありません。
全部で 560 人いると知ったら、彼はどこに立っているでしょうか。 回答 : n(候補者の数) を入力すると、選択されない 1 議席の値が出力されるプログラムを作成しようとしました。
循環リンクリストと削除を使用しました。
私はコーディングにかなり慣れていないので、ご容赦ください。
私のプログラムは、入力 2、4、8、16、32、64 などに対して動作します。これらすべての ans は 1 です。しかし、他の入力では動作しません。
#include <iostream>
using namespace std;
struct node
{
node* ptr;
int data;
}start;
int main()
{
node *start=NULL;
int n;
cout<<"Enter the number of students : ";
cin>>n;
node *temp=new node;
temp->data=1;
temp->ptr=NULL;
start=temp;
for(int x=2;x<=n;x++)
{
node* temp1=new node;
temp1->data=x;
temp->ptr=temp1;
temp1->ptr=start;
temp=temp1;
}
node* temp2=start;
do
{
cout<<temp2->data<<" ";
temp2=temp2->ptr;
}while(temp2!=start);
cout<<endl;
//delete bigins here
temp2=start;
node* temp3=temp2->ptr;
do
{
temp2->ptr=temp3->ptr;
temp3->ptr=NULL;
delete temp3;
temp2=temp2->ptr;
temp3=temp2->ptr;
}while(temp2->ptr!=start);
temp2=start;
do
{
cout<<temp2->data<<" ";
temp2=temp2->ptr;
}while(temp2!=temp3);
cout<<endl;
}