UVA10125 Sumsets

本文介绍了一种利用折半搜索解决特定数学问题的方法。通过将等式变形为a+b=d-c,采用枚举策略,结合使用map数据结构来存储a和b的组合,实现了高效的求解过程。代码实现简洁,通过两次O(n^2)操作,首先存储所有可能的a+b组合,然后逆序枚举d和c,检查是否存在符合题设条件的四元组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

嘟嘟嘟

很简单的折半搜索。
把式子变一下型,得到\(a + b = d - c\)
然后枚举\(a, b\),存到\(map\)里,再枚举\(c, d\)就好了。
\(map\)\(a,b\)两数之和为下标。为了判重,\(map\)的第二个参数是一个\(vector\)\(vector\)里面又存了两个数\(a, b\)
这样先\(O(n ^ 2)\)跑一边\(a, b\)之和,存到\(map\)里,然后从大到小枚举\(d\)\(c\),遍历\(map\)\(d - c\)\(vector\),如果四个数都没有一样的,就直接返回好了。
\(map\)的最大好处是代码特别短。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<stack>
#include<queue>
#include<map>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define Mem(a, x) memset(a, x, sizeof(a))
#define rg register
typedef long long ll;
typedef double db;
const int INF = 0x3f3f3f3f;
const db eps = 1e-8;
const int maxn = 1e3 + 5;
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, a[maxn];

struct Node
{
  int x, y;
};
map<int, vector<Node> > mp;

int solve()
{
  for(int i = n; i; --i)
      for(int j = 1; j < i; ++j)
    {
      int sum = a[i] - a[j];
      for(int k = 0; k < (int)mp[sum].size(); ++k)
        {
          int x = mp[sum][k].x, y = mp[sum][k].y;
          if(a[i] != x && a[i] != y && a[j] != x && a[j] != y)
        return a[i];
        }
    }
  return 536870912;
}

int main()
{
  while(scanf("%d", &n) && n)
    {
      mp.clear(); Mem(a, 0);
      for(int i = 1; i <= n; ++i) a[i] = read();
      sort(a + 1, a + n + 1);
      for(int i = 1; i < n; ++i)
    for(int j = i + 1; j <= n; ++j)
      mp[a[i] + a[j]].push_back((Node){a[i], a[j]});
      int ans = solve();
      if(ans == 536870912) puts("no solution");
      else write(ans), enter;
    }
  return 0;
}

转载于:https://www.cnblogs.com/mrclr/p/10022320.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值