-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek 10_MooreVotingAlgo.cpp
64 lines (60 loc) · 1.07 KB
/
week 10_MooreVotingAlgo.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<bits/stdc++.h>
using namespace std;
bool findMajority(int a[],int n)
{
int num=-1,c=0;
for(int i=0;i<n;i++)
{
if(c==0)
{
num=a[i];
c++;
}
else if(num==a[i])
c++;
else
c--;
}
int count=0;
for(int i=0;i<n;i++)
{
if(num==a[i])
count++;
}
if(count>=n/2)
return 1;
else
return 0;
}
float median(vector<int> &arr,int n)
{
if(n%2==0)
{
nth_element(arr.begin(),arr.begin()+n/2,arr.end());
nth_element(arr.begin(),arr.begin()+(n-1)/2,arr.end());
return (float)(arr[n/2]+arr[(n-1)/2])/2.0;
}
else
nth_element(arr.begin(),arr.begin()+n/2,arr.end());
return (float)arr[n/2];
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int result=findMajority(a,n);
if(result)
cout<<"Yes";
else
cout<<"No";
cout<<endl;
vector<int> arr(n);
for(int i=0;i<n;i++)
arr[i]=a[i];
float m=median(arr,n);
cout<<m<<endl;
return 0;
}