为啥dfs爆空间?

P1001 A+B Problem

OceanBrawl @ 2022-02-08 22:28:17

rt

#include <bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ewen using
#define ak namespace
#define ioi std
#define ewen_ak_ioi return 0;
ewen ak ioi;
ll in(){
    char c = getchar();
    int x = 0, f = 1;
    for (; c < '0' || c > '9'; c = getchar())
        if (c == '-') f = -1;
    for (; c >= '0' && c <= '9'; c = getchar())
        x = (x << 1) + (x << 3) + (c ^ 48);
    return x * f;
}
void put(int x){
    if (x < 0) x = -x, putchar('-');
    if (x > 9) put(x / 10);
    putchar(x % 10 + '0');
}
ll a,b;
void dfs(int x)
{
    if(x==a+b)
    {
        put(x);
        return;
    }
    if(x>a+b)dfs(x-1);
    else dfs(x+1);
    return;
}
int main()
{
    a=in();b=in();
    dfs(0);
    ewen_ak_ioi
}

by jia_shengyuan @ 2022-02-08 22:30:47

复杂度 O(\text{值域}) 显然会爆,二分应该能过(


by Ginger_he @ 2022-02-08 22:58:27

@BigPinkCat 建议用线段树


by dtrthg @ 2022-02-08 23:12:06

正解

#include <iostream>
using namespace std;
int a,b;
bool check(int mid)
{
    if(mid<=a+b) return true;
    return false;
}
int main()
{
    cin>>a>>b;
    int le=-2147483648,ri=2147483647;
    for(int i=1;i<=35;i++)
    {
        int mid=(le+ri)/2;
        if(check(mid)) le=mid;
        else ri=mid;
    }
    cout<<le<<endl;
    return 0;
}

by 5k_sync_closer @ 2022-02-09 08:07:03

@BigPinkCat 实际上你这个不爆空间也爆时间了,时空都是 O(\text{值域}) 的。


by OceanBrawl @ 2022-02-09 08:17:47

@jia_shengyuan 二分过过了,想试试dfs


by JasonXing @ 2022-02-15 13:55:26

开 O2


by Dream1234 @ 2022-02-18 21:00:45

管理员:不要再发出奇奇怪怪的答案,对于新手容易引起不适

言归正传

我对一个用dfs解a+b的人也是无语了

直接输出a+b它不香吗??

代码,上!

冲鸭!

#include<iostream>
using namespace std;
int main()
{
    int a,b;
    cin>>a>>b;
    cout<<a+b;
    return 0;
}

by TABS_Player @ 2022-03-12 09:09:22

@Dream1234 再快点

#include<iostream>
using namespace std;
int main()
{
    int a, b;
    scanf("%d %d", &a, &b);
    printf("%d", a + b);
    return 0;
}

cin改scanf, cout改printf。


by d2020csr @ 2022-04-10 19:40:24

深搜是万能的


by 10chen01 @ 2022-07-20 11:57:00

@d2020csr 广搜呢

最小生成树,最短路径,DP.......


|