ZR 染色(连通块)

满分做法:

由题,树是不需要染色的,所以我们要让所有的连通块变成树。所有联通块的总点数 是 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;    
}

猜你喜欢

转载自www.cnblogs.com/lihan123/p/11722717.html