解析: 这是很有意思并且很难的一道题。一开始我以为可以通过对时间按0.5s模拟蚂蚁的运动。很显然超时了。
最后通过求助书上的解析终于发现一个神秘的现象:蚂蚁不管是否转弯,最后总体的位置没有区别。
但是原先的蚂蚁有可能不是不转弯运动后的蚂蚁了,因此要知道谁是谁。
最后发现,不论蚂蚁怎么走,他们的相当位置不变,位于最左边的永远是最左边,掉下去的按负数距离记并且
不可能再相撞。蚂蚁不能跨域别的蚂蚁的身体,所以他只能局限一处运动。
首先记录蚂蚁的输入顺序id,在对蚂蚁按从小到大的位置排序。这样,第i个位置的蚂蚁是id[i]个输入的。
用order[id[i]] = i将其调换.这样,第i个蚂蚁是第order[i]个输入的。
1 //UVA 10881 piotr's Ants 2 //观察力 3 //难度:4.0 参考思路 4 //O(n^2)的时间复杂度 5 //如果遇到的问题你都能刨根问底,你就不用担心所学的东西没有掌握。 6 //因为作为程序员,我们有无数次犯错的机会,也有无数次改正的机会。 7 //没有知识,我要掌握知识;没有算法,我要创造算法! 8 #include <iostream> 9 using namespace std; 10 int main() 11 { 12 int i, j, t, ca,L, T,n; 13 struct ants{ 14 int x; 15 char to; 16 int id; 17 }ant[10005],after[10005]; 18 int order[10005]; //初始的位置序号 19 cin>>ca; 20 for(t=1;t<=ca;t++){ 21 cin>>L>>T>>n; 22 for(i=0;i<n;i++){ 23 cin>>ant[i].x; 24 cin>>ant[i].to; 25 ant[i].id = i; 26 } 27 for(i=0;i<n;i++) //按坐标排序 28 for(j=i+1;j<n;j++) 29 if(ant[i].x > ant[j].x){ 30 struct ants tm = ant[i]; 31 ant[i] = ant[j]; 32 ant[j] = tm; 33 } 34 for(i = 0; i < n; i++) 35 order[ant[i].id] = i; //第i个输入的位于位置order[i] 36 for(i = 0; i < n; i++){ 37 if(ant[i].to == 'L') 38 after[i].x = ant[i].x - T; //向左移动i个单位 39 else 40 after[i].x = ant[i].x + T; 41 after[i].to = ant[i].to; 42 } 43 for(i=0;i<n;i++) //按坐标排序 44 for(j=i+1;j<n;j++) 45 if(after[i].x > after[j].x){ 46 struct ants tm = after[i]; 47 after[i] = after[j]; 48 after[j] = tm; 49 } 50 cout<<"Case #"<<t<<':'<<endl; 51 for(i=0;i<n;i++){ 52 if(after[i].x < 0||after[i].x > L) 53 after[i].to = 'F'; 54 else 55 for(j=i+1;j<n;j++) 56 if(after[i].x==after[j].x&&after[i].to!='F') 57 after[i].to=after[j].to='T'; 58 } 59 for(i=0;i<n;i++){ 60 int a = order[i]; //第i个输入的位于位置a 61 switch(after[a].to){ 62 case 'L':cout<<after[a].x<<" L\n";break; 63 case 'R':cout<<after[a].x<<" R\n";break; 64 case 'F':cout<<"Fell off\n";break; 65 case 'T':cout<<after[a].x<<" Turning\n";break; 66 } 67 } 68 cout<<endl; 69 } 70 return 0; 71 }