题目:
机器人小R在看一个魔术表演,魔术师面前有一排共N个倒扣着的杯子,其中每一个下面都有一个小玩具
并且每个小玩具都是唯一的。魔术师飞快地变换杯子之后让小R猜其中
M个玩具
在哪个杯子里。由于机器人小R内置的程序只能记录杯子的数量N,小玩具初始的位置p,以及魔术师每次变换杯子的位置p1,p2。小R的主人希望你能写一个程序,帮助小R找出玩具。
格式:
输入格式: 第一行给定三个整数N,M,T,T为魔术师操作的次数;
接下来的N行,每行给定一个字符串;
之后的T行,每行给定两个位置p1,p2,位置从1开始计数;
最后
M行,每行给定一个字符串。
输出格式: M行,每行一个整数,表示杯子现在的序号。
代码部分
- 方法一:
#include <bits/stdc++.h>
using namespace std;
const int N=5e4+10;
string s[N];
map<string,int> op;
void swap(int a,int b)
{
string s1=s[a];
s[a]=s[b];
s[b]=s1;// 把s[a]和s[b]的两个字符串调换位置
op[s[a]]=a;// 重新存入map容器的op数组中
op[s[b]]=b;
}
int main ()
{
int n,m,t;cin>>n>>m>>t;
for(int i=1;i<=n;i++)
{
cin>>s[i];
op[s[i]]=i;
}
while(t--)
{
int p1,p2;cin>>p1>>p2;
swap(p1,p2);
}
while(m--)
{
string ch;cin>>ch;
cout<<op[ch]<<endl;
}
return 0;
}
- 方法二:(先调换op,再调换s数组)
#include <bits/stdc++.h>
using namespace std;
const int N=5e4+10;
string s[N];
map<string,int> op;
int main ()
{
int n,m,t;
cin>>n>>m>>t;
for(int i=1;i<=n;i++)
{
cin>>s[i];
op[s[i]]=i;
}
while(t--)
{
int x,y;cin>>x>>y;
swap(op[s[x]],op[s[y]]);
swap(s[x],s[y]);
}
for(int i=1;i<=m;i++)
{
string c;cin>>c;
cout<<op[c]<<endl;
}
return 0;
}