题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1025
就是排序,完全用的STL的sort... 竟然没有超时... 这道题有什么简单的好方法,给我说下,谢谢!
1 #include<iostream> 2 #include<string> 3 #include<vector> 4 #include<algorithm> 5 using namespace std; 6 7 struct Node 8 { 9 string id; 10 int ln; 11 int lr; 12 int grade; 13 int fr; 14 }; 15 16 bool comp(Node n1, Node n2) 17 { 18 if(n1.grade > n2.grade) 19 return true; 20 else if(n1.grade == n2.grade && n1.id < n2.id) 21 return true; 22 else 23 return false; 24 } 25 26 int transfer(string n) 27 { 28 int sum(0); 29 int radix(1); 30 for(int i=n.size()-1; i>=0; --i) 31 { 32 sum += (n[i]-'0')*radix; 33 radix *= 10; 34 } 35 return sum; 36 } 37 38 int main() 39 { 40 int n; 41 while(cin>>n) 42 { 43 vector<Node> all; 44 for(int i=0; i<n; ++i) 45 { 46 int m; cin>>m; 47 cin.ignore(); 48 vector<Node> input; 49 for(int j=0; j<m; ++j) 50 { 51 string in; 52 getline(cin, in); 53 string id(in, 0, 13); string grade(in, 14); 54 Node n={id, i+1, -1, transfer(grade), -1}; 55 input.push_back(n); 56 } 57 58 sort(input.begin(), input.end(), comp); 59 input[0].lr = 1; all.push_back(input[0]); 60 for(int k=1; k<input.size(); ++k) 61 if(input[k].grade == input[k-1].grade) 62 { 63 input[k].lr = input[k-1].lr; 64 all.push_back(input[k]); 65 } 66 else 67 { 68 input[k].lr = k+1; 69 all.push_back(input[k]); 70 } 71 } 72 sort(all.begin(), all.end(), comp); 73 all[0].fr = 1; 74 for(int k=1; k<all.size(); ++k) 75 if(all[k].grade == all[k-1].grade) 76 all[k].fr = all[k-1].fr; 77 else 78 all[k].fr = k+1; 79 cout<<all.size()<<endl; 80 for(int i=0; i<all.size(); ++i) 81 cout<<all[i].id<<" "<<all[i].fr<<" " 82 <<all[i].ln<<" "<<all[i].lr<<endl; 83 } 84 return 0; 85 }