跳到正文

个人记录

小算法&trick

North_encounter约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年3月9日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 1 分钟

版本

  1. v1当前

1.摩尔投票算法


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

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

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

模版(P2397):

C++
#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;
}

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

原文