Codeforces 268 B - Two Sets 搜索...

本文介绍了一种将一组整数划分为两个集合A和B的方法,遵循特定规则:若x属于A,则a-x也必须属于A;若x属于B,则b-x也必须属于B。通过DFS算法解决该问题,并提供完整的C++实现代码。

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

                 题意:

Little X has n distinct integers: p1, p2, ..., pn. He wants to divide all of them into two sets A and B. The following two conditions must be satisfied:

  • If number x belongs to set A, then number a - x must also belong to set A.
  • If number x belongs to set B, then number b - x must also belong to set B.

Help Little X divide the numbers into two sets or determine that it's impossible.

Input

The first line contains three space-separated integers n, a, b (1 ≤ n ≤ 105; 1 ≤ a, b ≤ 109). The next line contains n space-separated distinct integers p1, p2, ..., pn (1 ≤ pi ≤ 109).

Output

If there is a way to divide the numbers into two sets, then print "YES" in the first line. Then print n integers: b1, b2, ..., bn (bi equals either 0, or 1), describing the division. If bi equals to 0, then pi belongs to set A, otherwise it belongs to set B.

If it's impossible, print "NO" (without the quotes).

                          

                 题解:

                          因为一个数要么A要么属于B..那么将它们都先定为A..再把不符合的调整到B..由于改变了一个位置从A到B..会让若干的数也会变..用一个dfs来处理就好...


Program:

#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h> 
#include<string>
#include<queue>
#include<map>
#include<algorithm>
#define MAXN 100005
#define ll long long
#define oo 1e+10
#define eps 1e-10
using namespace std;  
struct node
{
      int w,id;
      bool operator<(node a) const
      {
              return w<a.w;
      }
}P[MAXN];
int ans[MAXN],n,a,b; 
int find(int x)
{
      int l,r,mid;
      l=1,r=n+1;
      while (r-l>1)
      {
              mid=r+l>>1;
              if (P[mid].w>x) r=mid;
                         else l=mid;
      }
      if (P[l].w!=x) return 0;
      return l;
}
bool dfs(int x)
{
      if (!x) return false;
      if (ans[P[x].id]) return true;
      ans[P[x].id]=1;   
      if (find(a-P[x].w))
        if (!dfs(find(a-P[x].w))) return false;
      if (!dfs(find(b-P[x].w))) return false;
      return true;
}
bool FindAns()
{
      int i;   
      memset(ans,0,sizeof(ans)); 
      for (i=1;i<=n;i++)
      { 
              if (find(a-P[i].w)) continue;
              if (!dfs(i)) return false;
      }
      puts("YES");
      for (i=1;i<n;i++) printf("%d ",ans[i]);
      printf("%d\n",ans[n]);
      return true;
}
int main()
{       
      int i;   
      scanf("%d%d%d",&n,&a,&b);
      for (i=1;i<=n;i++) scanf("%d",&P[i].w),P[i].id=i;
      sort(P+1,P+n+1);
      if (!FindAns()) puts("NO");      
      return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值