2573

本文介绍了一种寻找最优解的算法,并通过实例演示了如何利用该算法解决问题的过程。算法首先对输入数据进行排序,然后通过特定的逻辑计算出最优解及其构成元素。
/*
	不仅求最优解,还要过程,我的懒方法,执行两次。
*/

// include file
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <ctime>

#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <bitset>

#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <list>
#include <functional>

using namespace std;

// typedef
typedef __int64 LL;

// 
#define read freopen("in.txt","r",stdin)
#define write freopen("out.txt","w",stdout)

#define Z(a,b) ((a)<<(b))
#define Y(a,b) ((a)>>(b))

const double eps = 1e-6;
const double INFf = 1e100;
const int INFi = 1000000000;
const LL INFll = (LL)1<<62;
const double Pi = acos(-1.0);

template<class T> inline T sqr(T a){return a*a;}
template<class T> inline T TMAX(T x,T y)
{
	if(x>y) return x;
	return y;
}
template<class T> inline T TMIN(T x,T y)
{
	if(x<y) return x;
	return y;
}
template<class T> inline T MMAX(T x,T y,T z)
{
	return TMAX(TMAX(x,y),z);
}
template<class T> inline T MMIN(T x,T y,T z)
{
	return TMIN(TMIN(x,y),z);
}
template<class T> inline void SWAP(T &x,T &y)
{
	T t = x;
	x = y;
	y = t;
}


// code begin
int N,dt[1010];
int main()
{
	read;
	write;
	while(scanf("%d",&N)==1)
	{
		for(int i=1;i<=N;i++)
		{
			scanf("%d",dt+i);
		}
		sort(dt+1,dt+1+N);
		int ans = 0;
		for(int i=N;i>=1;i--)
		{
			if(i==1)
			{
				ans += dt[1];
				break;
			}
			else if(i==2)
			{
				ans += dt[2];
				break;
			}
			else if(i==3)
			{
				ans += dt[1]+dt[2]+dt[3];
				break;
			}
			else
			{
				if( dt[1]+dt[i-1]>2*dt[2])
				{
					ans += dt[2]+dt[1]+dt[i]+dt[2];
					i--;
				}
				else
				{
					ans += dt[i]+dt[1];
				}
			}
		}

		printf("%d\n",ans);

		for(int i=N;i>=1;i--)
		{
			if(i==1)
			{
				printf("%d\n",dt[1]);
				break;
			}
			else if(i==2)
			{
				printf("%d %d\n",dt[1],dt[2]);
				break;
			}
			else if(i==3)
			{
				printf("%d %d\n",dt[1],dt[3]);
				printf("%d\n%d %d\n",dt[1],dt[1],dt[2]);
				break;
			}
			else
			{
				if( dt[1]+dt[i-1]>2*dt[2])
				{
					printf("%d %d\n",dt[1],dt[2]);
					printf("%d\n",dt[1]);
					printf("%d %d\n",dt[i-1],dt[i]);
					printf("%d\n",dt[2]);
					i--;
				}
				else
				{
					printf("%d %d\n",dt[1],dt[i]);
					printf("%d\n",dt[1]);
				}
			}
		}
	}

	return 0;
}

转载于:https://www.cnblogs.com/ac2012/archive/2011/05/02/2034290.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值