总结:
某些需要搜索的情况下,
使用数组比使用链表快捷的多,如本题中通过下标的变化来搜索,使用链表则需要循环来消耗太多时间。
初做法:(几个测试点超时:80分)
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct list {int dir;char w[10];list* next;list* befo;
}node;
node* head=NULL;
int a[100001], s[100001];
int min(int a, int b)
{if (a < b)return a;return b;
}
int main()
{int n, m,i,j,sum;node* pr = NULL;node* nnode = (node*)malloc(sizeof(node));cin >>n >> m;for(i=0;i<n;i++){if(i!=0)nnode = (node*)malloc(sizeof(node));pr = NULL;if (head == NULL){head = nnode;pr = head;}else{for (pr = head; pr->next != NULL; pr = pr->next);pr->next = nnode;}cin >> nnode->dir;cin >> nnode->w;nnode->next = NULL;if(nnode!=head)nnode->befo = pr;}nnode->next = head;head->befo = nnode;for (i = 0; i < m; i++)cin >> a[i] >> s[i];node* find = head;for(i = 0; i < m; i++){int minone = min(s[i], n - s[i]);sum = a[i] + find->dir;if(sum==1){if(minone==s[i])for (j = 0; j < minone; j++)find = find->next;elsefor (j = 0; j < minone; j++)find = find->befo;}else{if (minone == s[i])for (j = 0; j < minone; j++)find = find->befo;elsefor (j = 0; j < minone; j++)find = find->next;}}cout << find->w;
}
数组做法:
#include<iostream>
#include<cstdio>
using namespace std;
struct node {int dir;char job[100];
};
node toy[100001];
int a[100001], s[100001];
int main()
{int n, m,i,j,ans;cin >> n >> m;for (i = 0; i < n; i++)cin >> toy[i].dir >> toy[i].job;for (i = 0; i < m; i++)cin >> a[i] >> s[i];ans = 0;for (j = 0; j < m; j++){if (a[j] + toy[ans].dir == 1){ans += s[j];if (ans > n-1)ans -= n;}else{ans -= s[j];if (ans < 0)ans += n;}}cout << toy[ans].job;}