0001 #include <cstdio> 0002 #include <cstring> 0003 #include <cstdlib> 0004 #include <ctime> 0005 #include "_share/util.h" 0006 #include "UniPrint/print.h" 0007 #include "vector/vector.h" 0008 #include "candidate.h" 0009 #include "majority.h" 0010 0011 int main(int argc, char* argv[]) { //多数元素算法测试 0012 if (2 > argc) { printf("Usage: %s <n>\a\a\n", argv[0]); return 1; } 0013 Rank n = atoi(argv[1]); 0014 if (n < 1) { printf("Invalid arguments\a\a\n"); return 1; } 0015 srand(31415926); //srand((uint32_t) time(nullptr)); //随机种子 0016 //随机生成向量 0017 Vector<int> A; //以整型为例 0018 int maj = rand() % n; printf("%d is highly possible to be a majority\n", maj); //随机确定一个maj候选 0019 while (A.size() < n) { //继续不断插入n,直至共有n个元素 0020 int ele = (rand() % 100 < 50) ? maj : rand() % n; //49%的概率确定是maj,51%随机(可实验不同概率的效果) 0021 A.insert(A.size(), ele); 0022 } 0023 print(A); //均匀随机置乱 0024 //计算多数元素 0025 majority(A, maj = -1) ? 0026 printf("Majority found as %d\n", maj) : 0027 printf("Majority NOT found\n"); 0028 //通过排序进一步验证 0029 A.sort(); print(A); 0030 //返回 0031 return 0; 0032 }