30分蒟蒻留下了悔恨的泪水,在线求助

P1197 [JSOI2008] 星球大战

HunteRRRRRRR @ 2020-01-20 23:15:04

题解的大佬都是用的邻接表 我用的是结构体,答案是对的,就是TLE,1.2s,题目限制是1s,大佬们能说说我这代码怎么优化吗=-=

#include <iostream>
#include <algorithm>
#include <vector>
#include <cstdio>
using namespace std;
const int maxn= 400010;
struct node{
    int x,y;
}v[maxn];
int pa[maxn],n,m,k,a,vis[maxn];
int find(int x){return pa[x]!=x?pa[x]=find(pa[x]):x;}
void Union(int x,int y){
    int px=find(x);
    int py=find(y);
    if(px!=py)
        pa[px]=py;
}
int main(){
    int cnt=0;
    scanf("%d%d",&n,&m);
    fill(vis,vis+400010,0);
    for(int i=0;i<400002;i++) pa[i]=i; 
    for(int i=0;i<m;i++){
        scanf("%d%d",&v[i].x,&v[i].y);
        Union(v[i].x,v[i].y);
    }
    for(int i=0;i<n;i++)
        if(pa[i]==i) cnt++;
    printf("%d\n",cnt);
    scanf("%d",&k);
    for(int i=0;i<k;i++){
        for(int j=0;j<400002;j++) pa[j]=j;
        int cnt1=0;
        scanf("%d",&a);
        vis[a]=1;
        for(int j=0;j<m;j++){
            if(vis[v[j].x]==1||vis[v[j].y]==1) continue;
            else Union(v[j].x,v[j].y);
        }
        for(int j=0;j<n;j++){
            if(pa[j]==j&&vis[j]==0) cnt1++;
        }
        printf("%d\n",cnt1);
    }
    return 0;
}

by a___ @ 2020-01-21 00:12:50

吸氧(


by HunteRRRRRRR @ 2020-01-21 18:49:50

@a___ 什么吸氧=-=


by a___ @ 2020-01-21 23:10:31

@HunteRRRRRRR 别写暴力,逆序合并(30分吸氧根本过不了)


by HunteRRRRRRR @ 2020-01-22 11:08:51

@a___ 好的大佬 我试试


by L__j @ 2020-02-21 10:21:43

吸氧是看题解


|