UVA 1614 Hell on the Markets (思維 + 構造)

思路:
關鍵在於1 <= ai <= i。
結論:[1, sum(i)] 可以由 [a1, ai]組成。
證明 : 數學歸納法,n = 1顯然成立,假設n = i成立
對n = i + 1時,需要湊出[sum(i) + 1, sum(i) + a(i +1)]
由於sum(i) >= i,  1 <= a(i + 1) <= i+1, sum(i + 1)捨去由[a1, ai]可湊出的值,證畢。(口胡證明)
實現:排序後從大往小取,由結論sum/2可得,進而sum/2 - ai, 可由[a1, ai-1]得到,可知最終畢有解。
#include <set>
#include <map>
#include <ctime>
#include <cmath>
#include <stack>
#include <queue>
#include <deque>
#include <cstdio>
#include <string>
#include <vector>
#include <cctype>
#include <sstream>
#include <utility>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <algorithm>
#define SF(a) scanf("%d", &a)
#define PF(a) printf("%d\n", a)  
#define SFF(a, b) scanf("%d%d", &a, &b)  
#define SFFF(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define SFFFF(a, b, c, d) scanf("%d%d%d%d", &a, &b, &c, &d)
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define FOR(i, a, b) for(int i = a; i < b; ++i)
#define ALL(a) (a).begin(), (a).end()
#define SZ(a) (int)(a).size()
#define PB push_back
#define LL long long
#define mod 10007
#define inf 1000007
#define eps 1e-5
using namespace std;
int buf[20];
int read() {
	int x = 0; char ch = getchar(); bool f = 0;
	while (ch < '0' || ch > '9') { if (ch == '-') f = 1; ch = getchar(); }
	while (ch >= '0' && ch <= '9') x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
	return f ? -x : x;
}
void write(int x) {
	if (!x) { putchar(48); return; }
	int l = 0; if (x < 0) putchar('-'), x = -x;
	while (x) buf[++l] = x % 10, x = x / 10;
	while (l) putchar(buf[l--] + 48);
}
//-------------------------chc------------------------------//
const int maxn = 100000 + 5;
struct Node {
	LL val;
	int idx;
	bool operator<(const Node &rhs) const {
		return val > rhs.val;
	}
}a[maxn]; 
bool flag[maxn];

int main() {
	//IN(); OUT();
	int n;
	while (~SF(n)) {
		CLEAR(flag, 0);
		LL sum = 0;
		FOR(i, 0, n)
			scanf("%lld", &a[i].val), a[i].idx = i, sum += a[i].val;
		bool ok = true;
		if (sum & 1) ok = false;
		else {
			LL target = sum / 2;
			sort(a, a + n);
			FOR(i, 0, n) {
				if (a[i].val <= target) target -= a[i].val, flag[a[i].idx] = true;
			}
			/*while (target) {	//錯誤做法,可能取重
				Node cur;
				cur.val = target;
				Node* pos = upper_bound(a, a + n, cur);
				pos--;
				target -= pos->val;
				flag[pos->idx] = true;
			}*/
		}
		puts(ok ? "Yes" : "No");
		if (ok) {
			printf("%d", flag[0] ? -1 : 1);
			FOR(i, 1, n) printf(" %d", flag[i] ? -1 : 1);
			putchar('\n');
		}
	}
	return 0;
}

發佈了222 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章