Go to diff to previous submission
/* * File: ants.c * Author: cteam057 * * Created on October 27, 2012, 12:39 PM */ #include <cstdlib> #include <cstdio> /* * */ int cycles, l; class Ant { public: double state, pos; int start, moved; Ant() { state = pos = start = moved = 0; } void operator=(Ant &b) { start=b.start; pos=b.pos; moved=b.moved; state=b.state; } }; int comp(const void* a, const void* b) { Ant* bx = (Ant *)b; Ant* ax = (Ant *)a; if(ax->start<bx->start) return -1; if(ax->start==bx->start) return 0; return 1; } int main(int argc, char** argv) { int a; int i, p, j, mov; char d; Ant *ants; while(scanf("%d %d", &l, &a)==2) { ants = new Ant[a]; cycles=0; for(i = 0; i < a; i++) { scanf("%d %c", &p, &d); ants[i].start=p; ants[i].pos=p; if(d == 'L') { ants[i].state = -0.5; if(p>cycles) cycles = p; } else { ants[i].state = 0.5; if((l-p)>cycles) cycles = l-p; }; } qsort(ants, a, sizeof(Ant), comp ); i = 0; while(i < cycles*2) { mov = l; for(j = 1; j<a; j++) { if(ants[j].state<0&&ants[j-1].state>0 && ants[j].pos-ants[j-1].pos<mov) mov = ants[j].pos-ants[j-1].pos; } ants[0].pos += ants[0].state*mov; if(ants[0].state) ants[0].moved = 1; else ants[0].moved = 0; if(ants[0].pos<=0 || ants[0].pos>=l) ants[0].state=0; for(j = 1; j < a; j++) { ants[j].pos += ants[j].state*mov; if(ants[j].state) ants[j].moved = 1; else ants[j].moved = 0; if(ants[j].pos==ants[j-1].pos) { ants[j].state*=-1; ants[j-1].state*=-1; } if(ants[j].pos<=0 || ants[j].pos>=l) ants[j].state=0; } i+=mov; } if(cycles==0) { if(ants[0].state<0) ants[0].moved=1; for(i = 1; i<a-1; i++) { ants[i].moved=0; } if(ants[a-1].state>0) ants[a-1].moved=1; } printf("The last ant will fall down in %d seconds - started at ", cycles); j = 0; for(i = 0; i < a; i++) { if(ants[i].moved&&j==0) { j++; printf("%d", ants[i].start); continue; } if(ants[i].moved&&j==1) { printf(" and %d", ants[i].start); break; } } printf(".\n"); delete ants; } return 0; }
--- c4.s1110.cteam057.ants.cpp.0.ants.cpp +++ c4.s1128.cteam057.ants.cpp.0.ants.cpp @@ -42,5 +42,5 @@ int main(int argc, char** argv) { int a; - int i, p, j; + int i, p, j, mov; char d; Ant *ants; @@ -64,11 +64,17 @@ qsort(ants, a, sizeof(Ant), comp ); - - for(i = 0; i < cycles*2; i++) { - ants[0].pos += ants[0].state; + i = 0; + while(i < cycles*2) { + mov = l; + for(j = 1; j<a; j++) { + if(ants[j].state<0&&ants[j-1].state>0 + && ants[j].pos-ants[j-1].pos<mov) mov = ants[j].pos-ants[j-1].pos; + } + + ants[0].pos += ants[0].state*mov; if(ants[0].state) ants[0].moved = 1; else ants[0].moved = 0; if(ants[0].pos<=0 || ants[0].pos>=l) ants[0].state=0; for(j = 1; j < a; j++) { - ants[j].pos += ants[j].state; + ants[j].pos += ants[j].state*mov; if(ants[j].state) ants[j].moved = 1; else ants[j].moved = 0; if(ants[j].pos==ants[j-1].pos) { @@ -78,4 +84,5 @@ if(ants[j].pos<=0 || ants[j].pos>=l) ants[j].state=0; } + i+=mov; }