TLE 求助

B3624 猫粮规划

Ker_White @ 2024-07-16 10:49:49

#include<bits/stdc++.h>
#define homo 114514
using namespace std;
int a[homo],l,r,n,sum=0,Mdata[homo],ts=0,b;
bool vis[homo];
void dfs(int x) {
    if(x == r+1) {
        ts=0;           
        for(int i=1;i<=r;i++)
        {
            ts+=Mdata[a[i]];
        }
        if(ts>=l && ts<=b)
        {
            sum++;
        }
        return; 
    }
    for(int i = a[x-1]+1; i<= n; i++) {
        if(vis[i] == false) {
            a[x] = i;
            vis[i] = true;
            dfs(x+1);
            vis[i] = false;
        }
    }
    return;
}
int main()
{
    cin>>n>>l>>b;
    for(int i=1;i<=n;i++)
    {
        cin>>Mdata[i];
        ts+=Mdata[i];
        if(Mdata[i]>=l && Mdata[i]<=b)
        {
            sum++;
        }   
    }
    if(ts>=l && ts<=b)
    {
        sum++;
    }
    for(int i=2;i<=n-1;i++)
    {
        r=i;
        dfs(1);
    }   
    cout<<sum;
    return 0;
}

6~#10 TLE!!!!!!!


by switchwanjia @ 2024-09-15 17:25:15

#include<bits/stdc++.h>
using namespace std;
int n,l,r,w[1000],ans=0;
void search(int p,int sum)
{
    if(sum>r)
        return;
    if(p>n)
    {
        if(sum>=l&&sum<=r)
            ans++;
        return;
    }
    search(p+1,sum);
    search(p+1,sum+w[p]);   
}
int main()
{
    ios::sync_with_stdio(0);
    cin>>n>>l>>r;
    for(int i=1;i<=n;++i)
        cin>>w[i];
    search(1,0);
    cout<<ans;
    return 0;
}

求关注


|