比较想知道$2^n$枚举为何 TLE 0pts
查看原帖
比较想知道$2^n$枚举为何 TLE 0pts
1414950
YYCk楼主2024/11/20 15:30

O(2n)O(2^n) 二进制子集枚举代码

#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int T;
int n;
int a[N];
int ans,sum;
int last,last2;
bool red[N],blue[N];
void baoli(){
    for(int i=0;i<(1<<n);i++){
        sum=0;
        last=-1;
        last2=-1;
        memset(red,0,sizeof(red));
        memset(blue,0,sizeof(blue));
        for(int j=0;j<n;j++){
            if(i&(1<<j)){
                red[j+1]=1;
                if(last==-1)    last=j+1;
            }
            else{
                blue[j+1]=1;
                if(last2==-1)   last2=j+1;
            }
        }
        for(int j=last+1;j<=n;j++){
            if(red[j]){
                if(a[j]==a[last])   sum+=a[j];
                last=j;
            }
        }                                                            
        for(int j=last2+1;j<=n;j++){
            if(blue[j]){
                if(a[j]==a[last2])   sum+=a[j];
                last2=j;
            }
        }
        ans=max(ans,sum);
    }
    cout<<ans<<"\n";
}
int main(){
    cin>>T;
    while(T--){
        cin>>n;
        ans=0;
        for(int i=1;i<=n;i++)   cin>>a[i];
        if(n<=25)
            baoli();
        else
            cout<<"0\n";
    }
    return 0;
}
2024/11/20 15:30
加载中...