标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32767 K (Java/Others)
Total Submission(s): 18818 Accepted Submission(s): 7603
这个问题比较简单,很多的前辈已经写过了,我最近做了一下,也提提我的拙见;
首先题目的大意是:给你一个项数为n的数列t,这个数列中有一个数出现的次数最多,并且出现的次数大于n/2;
我的思路是先排序,然后取t[n/2],t[n/2]就是这个数;
代码一:
sort排序的:561MS;
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<iomanip> 5 #include<cctype> 6 #include<string> 7 #include<cmath> 8 #include<cstdio> 9 #include<cstdlib> 10 #define LL long long 11 #define PF(x) ((x)*(x)) 12 #define LF(x) ((x)*PF(x)) 13 14 using namespace std; 15 const int INF=1<<31-1; 16 const int max9=1e9; 17 const int max6=1e6; 18 const int max3=1e3; 19 20 int gcd(int a,int b) 21 { 22 return b==0?a:gcd(b,a%b); 23 } 24 int t[max6+5]; 25 int main() 26 { 27 int n; 28 while(cin >> n) 29 { 30 for(int i=0;i<n;i++) cin >> t[i]; 31 sort(t,t+n); 32 cout << t[n/2] << endl; 33 } 34 return 0; 35 }
代码二:
qsort排序的:390MS
1 #include<iostream> 2 #include<algorithm> 3 #include<cstring> 4 #include<iomanip> 5 #include<cctype> 6 #include<string> 7 #include<cmath> 8 #include<cstdio> 9 #include<cstdlib> 10 #define LL long long 11 #define PF(x) ((x)*(x)) 12 #define LF(x) ((x)*PF(x)) 13 14 using namespace std; 15 const int INF=1<<31-1; 16 const int max9=1e9; 17 const int max6=1e6; 18 const int max3=1e3; 19 20 int gcd(int a,int b) 21 { 22 return b==0?a:gcd(b,a%b); 23 } 24 int t[max6+5]; 25 int comp(const void *a,const void *b) 26 { 27 return *(int *)a-*(int *)b; 28 } 29 int main() 30 { 31 int n; 32 while(cin >> n) 33 { 34 for(int i=0;i<n;i++) cin >> t[i]; 35 qsort(t,n,sizeof(t[0]),comp); 36 cout << t[n/2] << endl; 37 } 38 return 0; 39 }
HDU 1029 Ignatius and the Princess IV
标签:
原文地址:http://www.cnblogs.com/I-love-HLD/p/4298348.html