题目链接:Online Judge
根据刘汝佳的解法的思路,我的代码如下:
#include <cstdio>
#include <algorithm>
#include <string>
const int maxn = 10001;
struct ant{
int id;
int loc;
int dir;
};
bool cmp(const ant &a, const ant &b){
return a.loc < b.loc;
}
bool cmp1(const ant &a, const ant &b){
return a.id < b.id;
}
ant a[maxn], b[maxn];
int order[maxn];
int N, L, T, n;
char ch;
std::string direction[3] = {"L", "Turning", "R"};
int main(){
scanf("%d", &N);
for(int kase = 1; kase <= N; ++kase){
printf("Case #%d:\n", kase);
scanf("%d %d %d", &L, &T, &n);
for(int i = 0; i < n; ++i){
scanf("%d %c", &a[i].loc, &ch);
a[i].id = i;
a[i].dir = ch == 'L' ? -1 : 1;
}
std::sort(a, a + n, cmp);
for(int i = 0; i < n; ++i){
order[i] = a[i].id;
b[i].loc = a[i].loc + a[i].dir * T;
b[i].dir = a[i].dir;
}
std::sort(b, b + n, cmp);
for(int i = 0; i < n; ++i){
b[i].id = order[i];
if(i != n - 1 && b[i].loc == b[i + 1].loc){
b[i].dir = 0;
b[i + 1].dir = 0;
}
}
std::sort(b, b + n, cmp1);
for(int i = 0; i < n; ++i){
if(b[i].loc < 0 || b[i].loc > L){
printf("Fell off\n");
} else{
printf("%d %s\n", b[i].loc, direction[b[i].dir + 1].c_str());
}
}
printf("\n");
}
return 0;
}
我起先的代码如下,样例答案是对的,但提交时显示超时:
#include <cstdio>
#include <deque>
#include <set>
#include <algorithm>
struct ant{
int id;
int loc;
int direction;
bool turnFlag = false;
};
int N, L, T, n, loc;
char ch;
std::deque<ant> de;
std::set<int> fellOff;
bool cmp(const ant &a, const ant &b){
return a.loc < b.loc;
}
bool cmp1(const ant &a, const ant &b){
return a.id < b.id;
}
int main(){
scanf("%d", &N);
for(int kase = 1; kase <= N; ++kase){
scanf("%d %d %d", &L, &T, &n);
de.clear();
de.resize(n);
for(int i = 0; i < n; ++i){
scanf("%d %c", &de[i].loc, &ch);
de[i].id = i;
de[i].direction = ch == 'L' ? -1 : 1;
}
sort(de.begin(), de.end(), cmp);
for(int i = 0; i < T; ++i){
if(de[0].loc == 0 && de[0].direction == -1){
fellOff.insert(de[0].id);
de.pop_front();
}
if(de.back().loc == L && de.back().direction == 1){
fellOff.insert(de.back().id);
de.pop_back();
}
for(int j = 0; j < de.size(); ++j){
if(de[j].direction == -1){
de[j].loc--;
} else{
if(j == de.size() - 1){
de[j].loc++;
} else if(de[j + 1].loc > de[j].loc + 2 || de[j + 1].direction == 1){
de[j].loc++;
} else{
if(de[j + 1].loc == de[j].loc + 2){
de[j].loc++;
de[j + 1].loc--;
}
de[j].direction = -1;
de[j + 1].direction = 1;
j++;
}
}
}
}
for(int i = 0; i < de.size(); ++i){
if((i != de.size() - 1 && de[i + 1].loc == de[i].loc) || (i != 0 && de[i - 1].loc == de[i].loc)){
de[i].turnFlag = true;
}
}
sort(de.begin(), de.end(), cmp1);
int cur = 0;
printf("Case #%d:\n", kase);
for(int i = 0; i < n; ++i){
if(fellOff.find(i) != fellOff.end()){
printf("Fell off\n");
} else{
printf("%d ", de[cur].loc);
if(de[cur].turnFlag){
printf("Turning\n");
} else{
printf("%c\n", de[cur].direction == -1 ? 'L' : 'R');
}
cur++;
}
}
printf("\n");
fellOff.clear();
}
return 0;
}