AT_arc185_c [ARC185C] Sum of Three Integers

· · 题解

笔者建议先完成 AT_abc392_g,算得上是此题的弱化版。

考虑生成函数。设 a 中含有 c(i) 个 i,则生成函数为

g(a)=\sum_{i=1}^n c(i)x^i

然后,g(a)^2 中 x^s 项的系数 f(s) 的组合意义是:选两个下标 i,j 使 a_i+a_j=s 的方案数,并没有要求 i<j。为了求得保证 i<j 的方案数,考虑

f(a)\leftarrow \frac 1 2 (f(a)-c(\frac a 2))

回归本题,考虑枚举三个数中的一个,设其下标为 k,y=a_k。x 的定义同题面中。则现在只需要找 i,j 使得 a_i+a_j=x-y,(i,j) 的方案数已求。但是,是不是没有排除 i=k 或 j=k 的情况?为了除去这些情况,我们只需要知道 c(x-2y)。注意一下 x=3y 的情况。

如果发现此时的方案数还 >0,则继续枚举 i,找 j\neq i 且 j\neq k。按顺序输出即可。

其实我不会写 FFT。AtCoder Library 真是太好了。

// [ARC185C] Sum of Three Integers
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
#include <atcoder/convolution>
#define ll long long
#define rep(i, s, t) for(int i=s; i<=t; ++i)
#define debug(x) cerr<<#x<<":"<<x<<endl;
const int N=1000010;
using namespace std;
char buf[1<<21], *p1=buf, *p2=buf;
#define gc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++)
inline int read()
{
    int x=0, f=1; char c=gc();
    while(c<'0' || c>'9') c=='-' && (f=-1), c=gc();
    while('0'<=c && c<='9') x=(x<<3)+(x<<1)+c-'0', c=gc();
    return x*f;
}

int n, x, a[N]; vector<ll> c(N), f(N);
vector<int> vec[N];
bool solve(int i)
{
    rep(j, 1, n) if(j!=i && x>a[i]+a[j])
    {
        for(int k:vec[x-a[i]-a[j]])
        {
            if(k!=i && k!=j)
            {
                int ans[]={i, j, k};
                sort(ans, ans+3);
                printf("%d %d %d", ans[0], ans[1], ans[2]);
                return 1;
            }
        }
    }
    return 0;
}

int main()
{
    n=read(), x=read();
    rep(i, 1, n)
    {
        a[i]=read();
        c[a[i]]++; vec[a[i]].push_back(i);
    }
    f=atcoder::convolution(c, c);
    rep(i, 1, x)
    {
        if(i%2==0) f[i]-=c[i>>1];
        f[i]>>=1;
    }
    rep(i, 1, n) if(x>a[i])
    {
        int y=a[i], cur=f[x-y];
        if(x-y-y>0)
        {
            if(x-y-y==y) cur-=c[y]-1;
            else cur-=c[x-y-y];
        }
        if(cur)
        {
            if(solve(i)) return 0;
        }
    }
    puts("-1");

    return 0;
}