Struct

两个排序代码

 1 #include <algorithm>
 2 #include <iostream>
 3 #include <string.h>
 4 using namespace std;
 5 
 6 const int N=50;
 7 
 8 struct stu{
 9 char a[10];
10 int b;
11 };
12 stu ch[N];
13 
14 bool cmp(stu a1, stu b1)
15 {
16     int k=strcmp(a1.a, b1.a);
17     if(k>0) return false;
18     if(k<0) return true;
19     else return a1.b < b1.b;
20 }
21 
22 int main()
23 {
24     int n;
25     cin >> n;
26     for(int i=0; i<n; i++)
27         cin >> ch[i].a >> ch[i].b;
28     sort(ch, ch+n, cmp);
29     for(int i=0; i<n; i++)
30         cout << ch[i].a << " " << ch[i].b << endl;
31     return 0;
32 }
View Code
 1 #include <algorithm>
 2 #include <iostream>
 3 #include <string.h>
 4 using namespace std;
 5 
 6 const int N=50;
 7 
 8 struct stu{
 9     int a, b;
10 
11     bool operator < (const stu& other) const {
12         return a == other.a ? b < other.b : a < other.a;
13     }
14 };
15 stu p[N];
16 
17 int main(){
18     int n;
19     cin >> n;
20     for(int i=0; i<n; i++)
21         cin >> p[i].a >> p[i].b;
22     sort(p, p+n);
23     for(int i=0; i<n; i++)
24         cout << p[i].a << " " << p[i].b << endl;
25     return 0;
26 }
View Code

Problem Description:

   在一个平面坐标系上有很多的点,你的任务是将它们按到原点的距离从近到远排序。

Input:

输入包含多组数据。每组数据第一行一个n,代表点的数量。接下来有n行,每行两个整数x,y,代表点的坐标。(n<=1000,0<=x,y<=10000)

Output:

对于每组数据,输出n行,每行两个整数,空格隔开。如果出现距离一样的,优先输出x坐标小的。

Sample Input:

3
1 2
2 3
3 2

Sample Output:

1 2
2 3
3 2
 1 #include<iostream>
 2 #include<algorithm>
 3 using namespace std;
 4 
 5 struct stu{
 6 int a, b;
 7 };
 8 stu ch[1002];
 9 
10 bool cmp(stu x, stu y){
11     if(x.a*x.a+x.b*x.b == y.a*y.a+y.b*y.b) return x.a < y.a;
12     return x.a*x.a+x.b*x.b < y.a*y.a+y.b*y.b;
13 }
14 int main()
15 {
16     int n;
17     while(cin>>n)
18     {
19         for(int i=0; i<n; i++)
20             cin >> ch[i].a>> ch[i].b;
21         sort(ch, ch+n, cmp);
22         for(int i=0; i<n; i++)
23             cout << ch[i].a << " " <<ch[i].b << endl;
24     }
25     return 0;
26 }
View Code
原文地址:https://www.cnblogs.com/tony-/p/6092157.html