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

注意的细节,附代码

Posted by wtyyy at 2021-07-10 21:33:18 on Problem 3977
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#define ll long long
#define ull unsigned long long
#define db double
#define int ll
#define vi vector<int>
#define vii vector<vi >
#define pii pair<int, int>
#define pb push_back
#define mkp make_pair
using namespace std;
bool cmp(pii a, pii b) {
	return a.first == b.first ? a.second < b.second : a.first < b.first;
}
int mn, tot;
void update(int sum, int cnt) {//更新答案
	sum = sum<0?-sum:sum;
	if (sum < mn || (sum == mn && cnt < tot)) {
		mn = sum;
		tot = cnt;
	}
}
signed main() {
#ifdef _DEBUG
	freopen("out", "w", stdout);
#endif
	ios::sync_with_stdio(false);
	cin.tie(0);
	while (1) {
		mn = tot = 9e18;
		int n;
		cin >> n;
		if (!n) break;
		vi a(n);
		for (int i = 0; i < n; i++) {
			cin >> a[i];
		}
		map<int, int> mp;//用map去重
		int m = n/2;//折半枚举
		for (int i = 1; i < 1<<m; i++) {
			int cnt = 0, sum = 0;
			for (int j = 0; j < m; j++) {
				if (i >> j & 1) {
					cnt++;
					sum += a[j];
				}
			}
			if (!mp.count(sum)) mp[sum] = cnt;
			else mp[sum] = min(mp[sum], cnt);
			update(sum, cnt);
		}
		vector<pii >b;
		for (map<int, int>::iterator it = mp.begin(); it != mp.end(); it++) {
			b.pb(*it);
		}
		for (int i = 1; i < 1<<(n-m); i++) {
			int cnt = 0, sum = 0;
			for (int j = 0; j < (n-m); j++) {
				if (i >> j & 1) {
					cnt++;
					sum += a[m+j];
				}
			}
			update(sum, cnt);
			int t = lower_bound(b.begin(), b.end(), mkp(-sum, 0), cmp) - b.begin() - 1;//查找绝对值差值最小的
			if (t >= 0 && t < b.size()) {
				update(sum + b[t].first, cnt + b[t].second);
			}
			t++;//找两个,一个靠左的,一个靠右的
			if (t >= 0 && t < b.size()) {
				update(sum + b[t].first, cnt + b[t].second);
			}
		}
		cout << mn << ' ' << tot << '\n';
	}

	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