Uva 10881 Piotr’s Ants 蚂蚁

一根长度为 L 厘米的木棍上有 n 只蚂蚁,每只蚂蚁要么朝左爬,要么朝右爬,速度为 1 厘米/秒。当两只蚂蚁相撞时,二者同时调头(掉头用的时间忽略不计)。给出每只蚂蚁的初始位置和朝向,计算 T 秒之后每只蚂蚁的位置。

由于掉头用的时间可以忽略不计,所以可以直接看做两只蚂蚁对穿而过。于是可以很开心的直接把坐标按照方向进行加 / 减的处理。得到某只蚂蚁的最终坐标。

把棍子拉为无限长,然后通过模拟这个过程可以发现,蚂蚁的顺序是绝对的,最左边的蚂蚁绝不可能爬到其他蚂蚁的右边去。所以将最终坐标从小到大排序就能够得到这只蚂蚁最终的位置。当然,如果最终蚂蚁的位置坐标小于 0 或者大于 L 那么就直接判断为Fell off。

此外,从题目所给的数据可以看得出,蚂蚁并不是按照顺序输出的,因此用数组存下输入的顺序就OK了。

P.S : 注意每组数据之间有个空行。

附AC代码:

   1: #include <stdio.h>
   2: #include <math.h>
   3: #include <iostream>
   4: #include <cstdarg>
   5: #include <algorithm>
   6: #include <string.h>
   7: #include <stdlib.h>
   8: #include <string>
   9: #include <list>
  10: #include <vector>
  11: #include <map>
  12: #define LL long long
  13: #define M(a) memset(a, 0, sizeof(a))
  14: using namespace std;
  15:  
  16: void Clean(int count, ...)
  17: {
  18:     va_list arg_ptr; 
  19:     va_start (arg_ptr, count);
  20:     for (int i = 0; i < count; i++)
  21:         M(va_arg(arg_ptr, int*));
  22:     va_end(arg_ptr);
  23: }
  24:  
  25: typedef struct Ant
  26: {
  27:     int id, p, d;
  28:     bool operator < (const Ant& x) const
  29:     {
  30:         return p < x . p;
  31:     }
  32: }Ant;
  33: Ant now[10009], next[10009];
  34:  
  35: int tmp[10009];
  36:  
  37: int main()
  38: {
  39:     int T;
  40:     scanf("%d", &T);
  41:     for (int cnt = 1; cnt <= T; cnt++)
  42:     {
  43:         int l, t, n;
  44:         int p, d;
  45:         char c;
  46:         printf ("Case #%d:
", cnt);
  47:         scanf("%d%d%d", &l, &t, &n);
  48:         for (int i = 0; i < n; i++)
  49:         {
  50:             scanf("%d %c", &p, &c);
  51:             d = ((c == 'L') ? (-1) : (1));
  52:             now[i] = (Ant) {i, p, d};
  53:             next[i] = (Ant) {0, p + t * d, d};
  54:         }
  55:         sort(now, now + n);
  56:         for (int i = 0; i < n; i++)
  57:             tmp[now[i] . id] = i;
  58:         sort(next, next + n);
  59:         for (int i = 0; i < n; i++)
  60:             if (next[i] . p == next[i + 1] . p)
  61:                 next[i] . d = next[i + 1] . d = 0;
  62:         for (int i = 0; i < n; i++)
  63:         {
  64:             int temp = tmp[i];
  65:             if(next[temp] . p < 0 || next[temp] . p > l)
  66:                 puts("Fell off");
  67:             else
  68:             {
  69:                 printf("%d ", next[temp] . p);
  70:                 if (next[temp] . d == 0) puts("Turning");
  71:                 else puts((next[temp] . d == 1) ? ("R") : ("L"));
  72:             }
  73:         }
  74:         puts("");
  75:     }
  76:     return 0;
  77: }
原文地址:https://www.cnblogs.com/wuhenqs/p/3205245.html