Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

AC代码

Posted by linhui98 at 2016-10-29 09:38:37 on Problem 3977
(一堆二分和sort,好慢)
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define fs first 
#define se second 
#define INF 1e15 + 5
typedef long long LL;
const int M = 40;

bool cmp(pair<LL, LL> a, pair<LL, LL> b){
	if(a.fs == b.fs) return a.se < b.se;
	return a.fs < b.fs;
}

LL num[M];
pair<LL, LL> sum[1000000];

LL ab(LL x){
	if(x < 0) return -x;
	return x;
}

int main()
{
	int n;
	sum[0].fs = -INF, sum[0].se = 0;
	while(scanf("%d", &n) && n){
		memset(num, 0, sizeof(num));
		LL res = INF, ans = INF, anstot = INF;
		for(int i = 1; i <= n; i++)
		  scanf("%lld", &num[i]);
		if(n == 1){
		  printf("%lld 1\n", ab(num[1]));
		  continue;
		}
		int m = n - n / 2, cnt = 0;
		for(LL i = 0; i < (1<<m); i++){
		  LL sum2 = 0, tot = 0;
		  for(LL j = 0; (1<<j) <= i; j++)
		    if((i>>j) & 1)
			  sum2 += num[n/2+j+1], tot++;
		  sum[++cnt].fs = sum2;
		  sum[cnt].se = tot; 
		}
		sort(sum+1, sum+1+cnt, cmp);
		for(LL i = 1; i < (1<<n/2); i++){
		  LL sum1 = 0, tot = 0;
		  for(LL j = 0; (1<<j) <= i; j++)
		    if((i>>j) & 1)
		      sum1 += num[j+1], tot++;
		  int k2 = lower_bound(sum+1, sum+1+cnt, make_pair(-sum1, 0), cmp) - sum;
		  int k1 = lower_bound(sum+1, sum+1+cnt, make_pair(sum[k2-1].fs, 0), cmp) - sum;
		  if(k1 < 1) k1 = 1;
		  if(k1 > cnt) k1 = cnt;
		  if(k2 < 1) k2 = 1; 
		  if(k2 > cnt) k2 = cnt;
		  for(int j = k1; j <= k2; j++)
			if(ab(sum1 + sum[j].fs) < res || (ab(sum1 + sum[j].fs) == res && tot + sum[j].se < anstot)){
			  res = ab(sum1 + sum[j].fs);
			  ans = sum1 + sum[j].fs;
			  anstot = tot + sum[j].se;
			}
		}
		for(int i = 1; i <= cnt; i++)  sum[i].fs = ab(sum[i].fs);
		sort(sum+1, sum+1+cnt, cmp);
		int j = 1;
		if(sum[j].se == 0) j++;
		if(ab(sum[j].fs) < res || (ab(sum[j].fs) == res && sum[j].se < anstot)){
		  res = ab(sum[j].fs);
		  ans = sum[j].fs;
		  anstot = sum[j].se;
		}
		
		printf("%lld %lld\n", ab(ans), anstot);
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator