L2-017 People divide in groups (greedy)

topic link

https://pintia.cn/problem-sets/994805046380707840/problems/994805061056577536

ideas

Thinking greedily, if we first sort these people from small to large, and then divide them into two parts, then there must be two extreme parts, and because the two groups of people are likely to be close, so when nnWhen n is an even number, then directly split it into two piles of the same number of people, otherwise we should makeoutgoingthe number of people in that pile a little larger, so that we can increase the gap

code

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod 1000000007
#define endl "\n"
#define PII pair<int,int>
#define INF 0x3f3f3f3f

int n;

int main()
{
    
    
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n;
	vector<int> V(n);
	for(int i = 0;i < n; ++i) cin>>V[i];
	sort(V.begin(),V.end());
	int l = n/2,r = n - l;
	cout<<"Outgoing #: "<<r<<endl;
	cout<<"Introverted #: "<<l<<endl;
	int ans = 0;
	for(int i = 0;i < n; ++i) {
    
    
		if(i < l) ans -= V[i];
		else ans += V[i];
	}
	cout<<"Diff = "<<ans<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_46201544/article/details/123963483
Recommended