暴力解法求优化

P3367 【模板】并查集

cygnus_beta @ 2021-05-20 22:20:14

用vector和set写的暴力,有错误并且超时,求修改及优化(如何怎么优化也过不了就让我看题解去吧

代码:

#include<cstdio>
#include<string>
#include<vector>
//#include<ctime>
#include<set>
using namespace std;

vector<set<int>>ufs;
set<int>ufs_s;
string ans;
int m,n,x,y;
//double t;

void Union(set<int>&s1,set<int>&s2){
    for(int iter:s2)s1.insert(iter);
}

vector<set<int>>::iterator find(vector<set<int>>&sets,const int nn){
    for(auto set=sets.begin();set!=sets.end();set++)if(set->find(nn)!=set->end())return set;
    return sets.end();
}

/*void debug(vector<set<int>>& sets){
    int cnt=0;
    for(auto i=sets.begin();i!=sets.end();i++,cnt++){
        printf("set %d:\n",cnt);
        for(int j:*i)printf("%d ",j);
        putchar('\n');
    }
}*/

int main(){
    //freopen("P3367.in","r",stdin);
    //t=clock();
    scanf("%d%d",&n,&m);
    for(unsigned i=0;i<m;i++){
        //debug(ufs);
        scanf("%d%d%d",&n,&x,&y);
        if(n==1){
            if(find(ufs,x)!=ufs.end()){
                auto iter=find(ufs,y);
                if(iter!=ufs.end()){
                    Union(*find(ufs,x),*iter);
                    ufs.erase(iter);
                }//find y
                else{
                    ufs_s.insert(y);
                    Union(*find(ufs,x),ufs_s);
                }//not find y
            }//find x
            else if(find(ufs,y)!=ufs.end()){
                auto iter=find(ufs,x);
                if(iter!=ufs.end()){
                    Union(*find(ufs,y),*iter);
                    ufs.erase(iter);
                }//find x
                else{
                    ufs_s.insert(x);
                    Union(*find(ufs,y),ufs_s);
                }//not find x
            }//find y
            else{
                ufs_s.insert(x);
                ufs_s.insert(y);
                ufs.push_back(ufs_s);
            }//not find x and y
        }
        else{
            if(find(ufs,x)!=ufs.end() and find(ufs,x)==find(ufs,y))ans+="Y\n";
            else ans+="N\n";
        }//n=2
        ufs_s.clear();
    }
    printf("%s",ans.c_str());
    //printf("%lf",(clock()-t)/CLOCKS_PER_SEC);

    return 0;
}

by _caiji_ @ 2021-05-20 22:21:49

建议直接看题解,学习并查集


by cygnus_beta @ 2021-05-20 22:23:03

好的


|