题目描述
小南有一套可爱的玩具小人, 它们各有不同的职业。
有一天, 这些玩具小人把小南的眼镜藏了起来。 小南发现玩具小人们围成了一个圈,它们有的面朝圈内,有的面朝圈外。如下图:
这时singer告诉小南一个谜題: “眼镜藏在我左数第3个玩具小人的右数第1个玩具小人的左数第2个玩具小人那里。 ”
小南发现, 这个谜题中玩具小人的朝向非常关键, 因为朝内和朝外的玩具小人的左右方向是相反的: 面朝圈内的玩具小人, 它的左边是顺时针方向, 右边是逆时针方向; 而面向圈外的玩具小人, 它的左边是逆时针方向, 右边是顺时针方向。
小南一边艰难地辨认着玩具小人, 一边数着:
singer朝内, 左数第3个是archer。
archer朝外,右数第1个是thinker。
thinker朝外, 左数第2个是writer。
所以眼镜藏在writer这里!
虽然成功找回了眼镜, 但小南并没有放心。 如果下次有更多的玩具小人藏他的眼镜, 或是谜題的长度更长, 他可能就无法找到眼镜了 。 所以小南希望你写程序帮他解决类似的谜題。 这样的谜題具体可以描述为:
有 n个玩具小人围成一圈, 已知它们的职业和朝向。现在第1个玩具小人告诉小南一个包含 m条指令的谜題, 其中第 z条指令形如“左数/右数第 s,个玩具小人”。 你需要输出依次数完这些指令后,到达的玩具小人的职业。
输出格式:
输出一个字符串, 表示从第一个读入的小人开始, 依次数完 m条指令后到达的小人的职业。
输入格式:
输入的第一行包含两个正整数 n,m, 表示玩具小人的个数和指令的条数。
接下来 n行, 每行包含一个整数和一个字符串, 以逆时针为顺序给出每个玩具小人的朝向和职业。其中0表示朝向圈内, 1表示朝向圈外。保证不会出现其他的数。字符串长度不超过10且仅由小写字母构成, 字符串不为空, 并且字符串两两不同。 整数和字符串之问用一个空格隔开。
接下来 m行,其中第 z行包含两个整数 a,,s,,表示第 z条指令。若 a,= 0,表示向左数 s,个人;若a,= 1 ,表示向右数 s,个人。保证a,不会出现其他的数, 1≤ s,
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int n,m;
int x,cnt,nopos;
struct peo{
int dir;
int num;
string name;
}s[100001];
peo t;
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>s[i].dir>>s[i].name,s[i].num=i;
t=s[1],nopos=t.num;
for(int i=1;i<=m;i++){
cin>>x>>cnt;
if(t.dir==0&&x==1||t.dir==1&&x==0){
while(cnt--){
if(s[nopos].num==n) nopos=1;
else nopos++;
}
t=s[nopos];
continue;
}
else if(t.dir==0&&x==0||t.dir==1&&x==1){
while(cnt--){
if(s[nopos].num==1) nopos=n;
else nopos--;
}
t=s[nopos];
continue;
}
}
cout<<t.name;
return 0;
}
这种方法谁都能想到,但是很明显,逐个枚举过程中经过的小人是很慢的,这样显然过不了,80,然后我们就像能否直接跳过过程,直达目标小人?显然很简单:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int n,m;
int x,cnt,nopos;
struct peo{
int dir;
int num;
string name;
}s[100001];
peo t;
int main(){
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>s[i].dir>>s[i].name,s[i].num=i;
t=s[1],nopos=t.num;
for(int i=1;i<=m;i++){
cin>>x>>cnt;
if(t.dir==0&&x==1||t.dir==1&&x==0){
nopos=(nopos+cnt)%n;
t=s[nopos];
continue;
}
else if(t.dir==0&&x==0||t.dir==1&&x==1){
nopos=((nopos-cnt)%n+n)%n;
t=s[nopos];
}
}
cout<<t.name;
return 0;
}
好像这回靠谱了?提交,90分???回顾一下代码,貌似并没有错误,这个点卡了我10分钟。好的大家想,我读入的时候是从下标1开始读入,那有没有可能在模运算时结果变成了0,而0位置上并没有人。显然这是存在的,那么怎么解决?
很简单啊,把读入下标都改成0开始就好了,最后的AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;
int n,m;
int x,cnt,nopos;
struct peo{
int dir;
string name;
}s[100005];
int main(){
cin>>n>>m;
for(int i=0;i<n;i++) cin>>s[i].dir>>s[i].name;
for(int i=1;i<=m;i++){
cin>>x>>cnt;
if(s[nopos].dir==0&&x==1
||s[nopos].dir==1&&x==0)
nopos=(nopos+cnt)%n;
else
nopos=((nopos-cnt)+n)%n;
}
cout<<s[nopos].name;
return 0;
}
模拟关键靠细心,多读两遍题,多构思两遍再写,就没问题了