top1编程
← 返回题目
题解

【入门】宇宙总统

3 条题解

  • 0
    @ 2026-10-24 4:34:47

    1. 解题思路

    把候选人编号作为计数数组下标,逐票累加a[x]。再按编号从1到100寻找票数最多者,输出其编号。

    2. 坑点和注意事项

    n表示选票总数,候选人编号另有1到100的范围,不能把选票的位置当成候选人编号。票数相同时选编号较大者,因此从小到大扫描时使用大于或等于更新答案。计数数组101项并初始化为0,最多1000票,int足够。

    3. 复杂度

    • 时间复杂度:O(n+100),读入n票并扫描100个编号。
    • 空间复杂度:O(100),固定大小的普通计数数组。
    /*
    思路:用编号作为数组下标统计票数,再寻找票数最多的编号。
    关键:编号与计数要分开,不能把选票存储位置当成候选人编号。
    坑点:并列时要较大编号,从小到大扫描时等票也更新。
    时间复杂度:O(n+100)。
    空间复杂度:O(100);总票数最多1000,计数和编号使用int。
    */
    #include <bits/stdc++.h>
    using namespace std;
    int main()
    {
        int n, x, a[101] = {}, ans = 1;
        cin >> n;
        for (int i = 0; i < n; i++)
        {
            cin >> x;
            a[x]++;
        }
        for (int i = 2; i <= 100; i++)
        {
            // 后扫描的编号更大,同票时替换掉旧答案。
            if (a[i] >= a[ans])
            {
                ans = i;
            }
        }
        cout << ans << endl;
        return 0;
    }
    
    • 0
      @ 2026-7-29 0:06:22
      #include<bits/stdc++.h>
      using namespace std;
      int main(){
      	int n,t[105]={},x,ma=0,b;
      	cin>>n;
      	for(int i=1;i<=n;i++){
      		cin>>x;
      		t[x]++;
      	}
      	for(int i=1;i<=100;i++){
      		if(t[i]>=ma){
      			ma=t[i];
      			b=i;
      		}
      	}
      	cout<<b;
      	return 0;
      }
      
      • 0
        @ 2026-7-28 22:44:44
        #include<bits/stdc++.h>
        using namespace std;
        struct zt{
        	int bh,ps;
        }a[1010];
        bool cmp(zt a,zt b){
        	if(a.ps>b.ps||a.ps==b.ps&&a.bh>b.bh){
        		return true;
        	}
        	else{
        		return false;
        	}
        }
        int main(){
        	int n,x;
        	cin>>n;
        	for(int i=0;i<n;i++){
        		cin>>a[i].bh;
        		a[a[i].bh].ps++;
        	}
        	sort(a,a+n,cmp);
        	cout<<a[0].bh;
        	
        }
        
        • 1