依旧是记录手写队列的操作,也依旧是拿之前用stl的queue做的题改成了手写队列去验证队列的正确性
- 由于主要是队列操作,所以题就不去解释了
poj 3278
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <string>
#include <cmath>
#include <cstdlib>
using namespace std;
struct Qnode
{
int data;
Qnode *next;
}qnode;
struct Queue
{
Qnode *head;
Qnode *tail;
};
//构造一个空队列
void InitQueue(Queue &Q)
{
Q.head = Q.tail = new Qnode;
if(Q.head == NULL){
cout<<"内存分配失败"<<endl;
exit(0);
}
Q.head->next = NULL;
}
//销毁队列
void DestryQueue(Queue &Q)
{
while(Q.head){
Q.tail = Q.head->next;
free(Q.head);
Q.head = Q.tail;
}
}
//向队列中压入元素
void Push(Queue &Q , int data)
{
Qnode *p = new Qnode;
p->data = data;
p->next = NULL;
Q.tail ->next = p;
Q.tail = p;
}
//获得队列头部元素
int GetHead(Queue &Q)
{
return Q.head->next->data;
}
bool Empty(Queue &Q)
{
if(Q.head == Q.tail) return true;
return false;
}
//出队列
void Pop(Queue &Q)
{
//若队列为空,则直接退出,反之删除队列的第一个元素
if(Empty(Q)){
cout<<"The Queue is empty"<<endl;
exit(0);
}
Qnode *p = Q.head->next;
Q.head->next = p->next;
//如果删除的元素正好是尾节点的元素,就让尾节点等于头节点
if(Q.tail == p){
Q.tail = Q.head;
}
delete p;
}
int main()
{
std::ios::sync_with_stdio(false);
int n,k,vis[100005];
Queue Q;
InitQueue(Q);
cin>>n>>k;
int ret[100001] = {0};
Push(Q, n);
vis[n] = 1;
while( !Empty(Q) ){
int x = GetHead(Q);
Pop(Q);
if(x - 1 >= 0 && !vis[x - 1] ){
Push(Q, x - 1);
vis[x - 1] = 1;
ret[x - 1] = ret[x] + 1;
}
if(x - 1 == k){
break;
}
if(x * 2 < 100001 && vis[x * 2] == 0){
Push(Q, x * 2);
vis[x *2] = 1;
ret[x * 2] = ret[x] + 1;
}
if(2 * x == k){
break;
}
if(x + 1 < 100001 && vis[x + 1] == 0){
Push(Q, x + 1);
vis[x + 1] = 1;
ret[x + 1] = ret[x] + 1;
}
if(x + 1 == k){
break;
}
}
cout<<ret[k]<<endl;
return 0;
}