zoukankan      html  css  js  c++  java
  • [TJOI2010]分金币

    嘟嘟嘟


    看数据范围,就能想到折半搜索。
    但怎么搜,必须得想清楚了。
    假设金币总数为1000,有20个人,首先搜前10个人,把答案记下来。然后如果在后十个人中搜到了4个人,价值为120,那么我们应该在记录的答案中的6个人中找价值最接近380的。
    luogu的第一篇题解写的特别好,没有用set,而是以人数为第一关键字,价值为第二关键字排序。这样保证了同一人数的金币是单调的,就可以二分查找了。

    #include<cstdio>
    #include<iostream>
    #include<cmath>
    #include<algorithm>
    #include<cstring>
    #include<cstdlib>
    #include<cctype>
    #include<vector>
    #include<stack>
    #include<queue>
    #include<set>
    using namespace std;
    #define enter puts("") 
    #define space putchar(' ')
    #define Mem(a, x) memset(a, x, sizeof(a))
    #define In inline
    typedef long long ll;
    typedef double db;
    const ll INF = 1e18;
    const db eps = 1e-8;
    const int maxn = 35;
    inline ll read()
    {
    	ll ans = 0;
    	char ch = getchar(), last = ' ';
    	while(!isdigit(ch)) last = ch, ch = getchar();
    	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
    	if(last == '-') ans = -ans;
    	return ans;
    }
    inline void write(ll x)
    {
    	if(x < 0) x = -x, putchar('-');
    	if(x >= 10) write(x / 10);
    	putchar(x % 10 + '0');
    }
    
    int n, m, a[maxn];
    struct Node
    {
    	int num; ll sum;
    	In bool operator < (const Node& oth)const
    	{
    		return num < oth.num || (num == oth.num && sum < oth.sum);
    	}
    }t[1 << (maxn >> 1)];
    ll tp[1 << (maxn >> 1)];
    int cnt = 0, l[maxn >> 1];
    
    ll Sum = 0, ans = INF;
    In void calc(int num, ll sum)
    {
    	if(num < 0) return;
    	int pos = lower_bound(tp + l[num], tp + l[num + 1], (Sum >> 1) - sum) - tp;
    	if(pos < l[num + 1]) ans = min(ans, abs(Sum - ((sum + tp[pos]) << 1)));
    	if(pos > l[num]) ans = min(ans, abs(Sum - ((sum + tp[pos - 1]) << 1)));
    }
    
    int main()
    {
    	int T = read();
    	while(T--)
    	{
    		ans = INF; cnt = 0; Sum = 0;
    		n = read(); m = n >> 1;
    		for(int i = 1; i <= n; ++i) a[i] = read(), Sum += a[i];
    		for(int i = 0; i < (1 << m); ++i)
    		{
    			int num = 0; ll sum = 0;
    			for(int j = 0; j < m; ++j) 
    				if((i >> j) & 1) ++num, sum += a[j + 1];
    			t[++cnt] = (Node){num, sum};
    		}
    		sort(t + 1, t + cnt + 1);
    		for(int i = 1; i <= cnt; ++i) tp[i] = t[i].sum;
    		for(int i = 1; i <= cnt; ++i) if(t[i].num ^ t[i - 1].num) l[t[i].num] = i;
    		l[m + 1] = cnt + 1;
    		for(int i = 0; i < (1 << (n - m)); ++i)
    		{
    			int num = 0; ll sum = 0;
    			for(int j = 0; j < n - m; ++j)
    				if((i >> j) & 1) ++num, sum += a[j + m + 1];
    			calc(m - num, sum);
    		}
    		write(ans), enter;
    	}
    	return 0;
    }
    
  • 相关阅读:
    分数的表示和运算
    用户管理
    DML,DDL
    索引
    sql语句执行顺序
    伪劣
    序列
    视图
    完整性约束
    ASP.NET MVC学习笔记(二)登陆验证
  • 原文地址:https://www.cnblogs.com/mrclr/p/10307259.html
Copyright © 2011-2022 走看看