• bzoj 1015: [JSOI2008]星球大战starwar 并查集


    题目链接:

    http://www.lydsy.com/JudgeOnline/problem.php?id=1015

    题意:

    题解:

    逆向思维+并查集。

    处理连通这让我们想到并查集,题目中的输入是一次破坏哪一个结点,我们可以逆着想,在剩余结点的基础上反向逐个加入被删除的结点,使每个结点与其相邻的并且处在目前未删除点集中的结点合并、tot维护联通块的数目、ans存储每次的tot。

    代码:

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 typedef long long ll;
     4 #define MS(a) memset(a,0,sizeof(a))
     5 #define MP make_pair
     6 #define PB push_back
     7 const int INF = 0x3f3f3f3f;
     8 const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
     9 inline ll read(){
    10     ll x=0,f=1;char ch=getchar();
    11     while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    12     while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    13     return x*f;
    14 }
    15 //////////////////////////////////////////////////////////////////////////
    16 const int maxn = 4e5+10;
    17 
    18 int fa[maxn],del[maxn],vis[maxn];
    19 vector<int> G[maxn],ans;
    20 
    21 int find(int x){
    22     return fa[x]==x ? x : fa[x]=find(fa[x]);
    23 }
    24 
    25 int main(){
    26     int n=read(),m=read();
    27     for(int i=1; i<=m; i++){
    28         int u,v;scanf("%d%d",&u,&v);
    29         G[u].push_back(v);
    30         G[v].push_back(u);
    31     }
    32 
    33     for(int i=0; i<=n; i++)
    34         fa[i] = i;
    35 
    36     int k = read();
    37     int tot = n-k;
    38     for(int i=1; i<=k; i++) del[i]=read(),vis[del[i]]=1;
    39 
    40     for(int u=0; u<n; u++){
    41         if(!vis[u]){
    42             for(int j=0; j<(int)G[u].size(); j++){
    43                 int v = G[u][j];
    44                 if(!vis[v]){
    45                     int t1 = find(u), t2 = find(v);
    46                     if(t1!=t2) fa[t1]=t2,tot--;                 
    47                 }
    48             }
    49         }
    50     }
    51 
    52     ans.push_back(tot);
    53 
    54     for(int i=k; i>=1; i--){
    55         int u = del[i];
    56         vis[u] = 0;
    57         tot++;
    58         for(int i=0; i<(int)G[u].size(); i++){
    59             int v = G[u][i];
    60             if(!vis[v]){
    61                 int t1=find(u),t2=find(v);
    62                 if(t1!=t2) fa[t1] = fa[t2],tot--;
    63             }
    64         }
    65         ans.push_back(tot);
    66     }
    67     for(int i=ans.size()-1; i>=0; i--){
    68         printf("%d
    ",ans[i]);
    69     }
    70 
    71     return 0;
    72 }
  • 相关阅读:
    WEBAPI 增加身份验证
    C# Image与Base64编码互转函数
    WebApi 接口传参接参
    Spring.Net依赖注入(属性注入)学习笔记
    ASP.NET MVC5+EF6+EasyUI 后台管理系统(30)-本地化(多语言)
    文件各种上传,离不开的表单
    linux下yum命令出现Loaded plugins: fastestmirror
    linux系统快速安装宝塔
    微信小程序实现watch属性监听数据变化
    chrome调试微信
  • 原文地址:https://www.cnblogs.com/yxg123123/p/6827645.html
Copyright © 2020-2023  润新知