小算法&trick

· · 个人记录

1.摩尔投票算法

date:2025年3月9日19:11:23

用途:用于求数列中多数元素。

核心内容:维护两个变量 ans 和 cnt,分别表示候选数字和它的“票数”(目前剩余的出现次数),在 cnt 为零时设定当前数字为候选数字,否则,若当前数字与候选数字相等票数加一,否则减一。

模版(P2397):

#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=5e5+20;
int ans,cnt;
int n;
int x;
inline int read(){
    int f=1,k=0;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-'){
            f=-1;
        }
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        k=(k<<1)+(k<<3)+(c^48);
        c=getchar();
    }
    return f*k;
}
signed main(){
    n=read();
    for(int i=1;i<=n;i++){
        x=read();
        if(cnt==0){
            ans=x;
            cnt++;
        }else{
            if(ans==x){
                cnt++;
            }else{
                cnt--;
            }
        }
    }
    cout<<ans;
    return 0;
}

学习原因:数据结构的小策略