码迷,mamicode.com
首页 > 其他好文 > 详细

ZR 染色(连通块)

时间:2019-10-22 22:18:39      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:iostream   code   type   ios   style   color   namespace   other   mes   

满分做法:

由题,树是不需要染色的,所以我们要让所有的连通块变成树。所有联通块的总点数 是 n,所以如果设联通块数为 C,则最后剩下的边个数就是 n − C,因此答案就是 m − n + C。

#include<cstring>
#include<queue>
#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<vector>
using namespace std;
typedef long long ll;
const int maxm=4e5+7;
int pre[maxm],last[maxm],other[maxm],l;
int n,m,ans;
bool vis[maxm];
void add(int x,int y)
{
 l++;
 pre[l]=last[x];
 last[x]=l;
 other[l]=y;
}
void dfs(int x)
{
 vis[x]=1;
 for(int p=last[x];p;p=pre[p])
 {
   int v=other[p];
   if(vis[v]) continue;
   dfs(v);
 }    
}
int main()
{
 scanf("%d%d",&n,&m);
 for(int i=1;i<=m;i++)
 {
  int x,y;
  scanf("%d%d",&x,&y);
  add(x,y);
  add(y,x);
 }
 for(int i=1;i<=n;i++)
 {
   if(vis[i]==0)
   {
        dfs(i);
        ans++;
   }
 }
 printf("%d\n",m-n+ans);
 return 0;    
}

 

ZR 染色(连通块)

标签:iostream   code   type   ios   style   color   namespace   other   mes   

原文地址:https://www.cnblogs.com/lihan123/p/11722717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!