【洛谷】P1563 玩具谜题
主要wa点是在转圈数数时容易忽略很多越界的问题。其实主要就正转跟反转两种转法。正转:转完求余总人数;反转:转完化成正数再求余总人数。
题解如下:
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
struct toys{
int dir;
string name;
};
int main()
{
int n,m;
cin>>n>>m;
toys toy[n+1];
int instr[m][2];
for(int i=0;i<n;i++)
{
cin>>toy[i].dir>>toy[i].name;
}
for(int i=0;i<m;i++)
{
cin>>instr[i][0]>>instr[i][1];
}
int tmp=0;
for(int i=0;i<m;i++)
{
if(instr[i][0]==0) //左数
{
if(toy[tmp].dir==0) //小人朝里
{
tmp=(tmp-instr[i][1]+n)%n;
}
else if(toy[tmp].dir==1) //小人朝外
{
tmp=(tmp+instr[i][1])%n;
}
}
else if(instr[i][0]==1) //右数
{
if(toy[tmp].dir==0) //小人朝里
{
tmp=(tmp+instr[i][1])%n;
}
else if(toy[tmp].dir==1) //小人朝外
{
tmp=(tmp-instr[i][1]+n)%n;
}
}
}
cout<<toy[tmp].name<<endl;
return 0;
}
其实完全可以不用输入的那个数组,直接边输入边转圈。
优化如下:
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
struct toys{
int dir;
string name;
};
int main()
{
int n,m;
cin>>n>>m;
toys toy[n+1];
for(int i=0;i<n;i++)
{
cin>>toy[i].dir>>toy[i].name;
}
int a,b;
int tmp=0;
for(int i=0;i<m;i++)
{
cin>>a>>b;
if(a==0) //左数
{
if(toy[tmp].dir==0) //小人朝里
{
tmp=(tmp-b+n)%n;
}
else if(toy[tmp].dir==1) //小人朝外
{
tmp=(tmp+b)%n;
}
}
else if(a==1) //右数
{
if(toy[tmp].dir==0) //小人朝里
{
tmp=(tmp+b)%n;
}
else if(toy[tmp].dir==1) //小人朝外
{
tmp=(tmp-b+n)%n;
}
}
}
cout<<toy[tmp].name<<endl;
return 0;
}