Q
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 1832 | Accepted: 1259 |
Description
You've got a queue. And you just got to mess with it.
Given a queue of items and a series of queue operations, return the resulting queue.
Queue operations are defined as follows:
starting-position to requested-position
meaning one wants the item at the starting position to be moved to the requested position. So if the queue of items were:
Item1 Item2 Item3 Item4 Item5
(Item1 being in position 1, Item2 in position 2, etc.)
after applying the queue operation:
5 to 2
the resulting queue would be:
Item1 Item5 Item2 Item3 Item4
as Item5 (the item in position 5) was moved to position 2. Multiple queue operations are applied at the same time, however; e.g., given the queue of items:
Item1 Item2 Item3 Item4 Item5 Item6 Item7 Item8
If the following queue operations were applied:
2 to 6; 6 to 3; 4 to 5; 5 to 2; 7 to 4; 8 to 1
then the resulting queue would be:
Item8 Item5 Item6 Item7 Item4 Item2 Item1 Item3
As you can see, the queue operations are strictly enforced, with other items (not involved in queue operations) maintaining their order and moving to vacant positions in the queue. Note that no two queue operations will have the same starting-position or same requested-position defined.
Input
Input to this problem will begin with a line containing a single integer x indicating the number of datasets. Each data set consists of three components:
- Start line – A single line, "m n" (1 <= m, n <= 20) where m indicates the number of items in the queue and n indicates the number of queue operations.
- Queue items – A line of short (between 1 and 8 characters) alphanumeric names for the items in the queue. Names are unique for a given data set and contain no whitespace.
- Queue operations – n lines of queue operations in the format "starting-position requested-position".
Output
For each dataset, output the queue after the queue operations have been applied. Print the elements of the queue on a single line, starting from the first and ending with the last, with a single space separating each item.
Sample Input
3 5 1 alpha beta gamma delta epsilon 5 2 8 6 a b c d e f g h 2 6 6 3 4 5 5 2 7 4 8 1 3 2 foo bar baz 3 1 1 3
Sample Output
alpha epsilon beta gamma delta h e f g d b a c baz bar foo
Source
大致题意:
给出一列字符串,要求按照所给变换形式得到新的字符串序列
如 5 2即将原序列第五个字符串放到新序列第二个位置,然后新序列剩下的空位置按照原字符串顺序补齐
解题思路:
设置两个数组que,visit分别表示新序列位置上存放的字符串序号,及字符串是否放入了新序列。
代码:
#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main()
{
int N;
cin>>N;
while(N--)
{
int i,j,n,m;
int que[25];
int visit[25];
string str[25];
char tmp[15];
cin>>n>>m;
for(i=1;i<=n;i++)
{
scanf("%s",tmp);
str[i]=tmp;
que[i]=-1;
visit[i]=0;
}
while(m--)
{
int a,b;
cin>>a>>b;
que[b]=a;
visit[a]=1;
}
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(que[i]==-1&&visit[j]==0)
{
que[i]=j;
visit[j]=1;
}
}
}
for(i=1;i<=n;i++)
cout<<str[que[i]]<<" ";
cout<<endl;
}
return 0;
}