cf#106-C. Division into Teams-贪心

http://codeforces.com/problemset/problem/149/C

题意:

给n个数,要求平均分成两堆,(偶数则每堆n/2个数,奇数则一堆比另一堆多1个数)


要求两堆最后的总和之差的绝对值 《 max(a[i])(最大元素值)


也就是尽可能平均就好啦。直接sort,然后往两边丢,每次丢两个,哪一堆比较小,就往哪一堆丢一个大的元素

......居然过了。。



#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <iostream>
using namespace std;
 
const double pi=acos(-1.0);
double eps=0.000001; 
 
struct node
{
	int x;
	int id;
};
node tm[100005];
bool cmp(node a,node b)
{
	return a.x>b.x;
}
int ans1[100005];
int ans2[100005];

int main()
{

	int n;
	int i;
	cin>>n;
	int maxx=0;
	for (i=1;i<=n;i++)
	{
		scanf("%d",&tm[i].x);
		if (tm[i].x>maxx)  maxx=tm[i].x;
		tm[i].id=i;
	}
	sort(tm+1,tm+1+n,cmp);
	
	int cun1=0;
	int cun2=0;
	int sum1=0;
	int sum2=0;
	if (n%2==0)
	{
		for (i=n;i>=1;i-=2)
		{
			if (sum1<sum2)
			{
			ans1[++cun1]=tm[i].id;
			ans2[++cun2]=tm[i-1].id;
			}
			else
			{
			ans1[++cun1]=tm[i-1].id;
			ans2[++cun2]=tm[i].id; 
			}
		} 
	}
	else
	{
			for (i=n;i>1;i-=2)
		{
			if (sum1<sum2)
			{
			ans1[++cun1]=tm[i].id;
			ans2[++cun2]=tm[i-1].id;
			sum1+=tm[i].x;
			sum2+=tm[i-1].x;
			}
			else
			{
			ans1[++cun1]=tm[i-1].id;
			ans2[++cun2]=tm[i].id; 
			sum1+=tm[i-1].x;
			sum2+=tm[i].x;
			}
		} 
		if (sum1>sum2)
		{
			sum2+=tm[1].x;
			ans2[++cun2]=tm[1].id;
		} 
		else
		{
			sum1+=tm[1].x;
			ans1[++cun1]=tm[1].id; 
		} 

	}
	
	printf("%d\n",cun1);
	for (i=1;i<=cun1;i++)
	{
		if (i!=1 ) printf(" ");
		printf("%d",ans1[i]);
	}
	printf("\n");
	printf("%d\n",cun2);
	for (i=1;i<=cun2;i++)
	{
		if (i!=1 ) printf(" ");
		printf("%d",ans2[i]);
	}
	printf("\n");







	return 0;
 
}


你可能感兴趣的:(cf#106-C. Division into Teams-贪心)