UVa 12166 - Equilibrium Mobile

dfs类的题,感觉应该还能再优化,时间用了0.9s+,挺长的。。

#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
struct Node{
    string s;
    unsigned long long t;
    Node *left,*right;
    Node():t(0),left(NULL),right(NULL){}
};
Node *root;
int cnt1,cnt2,cnt;
vector<unsigned long long>heavy;
Node* newnode(){
    return new Node;
}
void build(Node* a,int n){
    int i,k=0;
    if(a->s.find("[")==string::npos){
        stringstream ss(a->s);
        ss>>a->t;
        cnt1++;
        heavy.push_back(a->t<<n);
        return;
    }
    a->left=newnode();
    for(i=1;i<a->s.length();i++){
        if(a->s[i]=='[') k++;
        if(a->s[i]==']') k--;
        if(!k&&a->s[i]==',') break;
        a->left->s+=a->s[i];
    }
    a->right=newnode();
    for(i++;i<a->s.length()-1;i++)
        a->right->s+=a->s[i];
    build(a->left,n+1);
    build(a->right,n+1);
    return;
}
int main(){
    int t;
    cin>>t;
    while(t--){
        string s;
        cin>>s;
        cnt1=0;
        cnt2=cnt=1;
        root=newnode();
        root->s=s;
        build(root,0);
        sort(heavy.begin(),heavy.end());
        for(int i=0;i<heavy.size()-1;i++){
            if(heavy[i]==heavy[i+1]) cnt++;
            else cnt=1;
            cnt2=max(cnt2,cnt);
        }
        cout<<cnt1-cnt2<<endl;
        heavy.clear();
    }
    return 0;
}

你可能感兴趣的:(UVa 12166 - Equilibrium Mobile)