題目鏈接:http://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=2191
題意:題目意思是輸入n個點,再輸入m條邊,邊可以重複;
問加上第a,b之間的邊的時候有多少個迴路。
思路:將所有點建立一個並查集
(1)如果要插入的a,b點在同一個集合,則再插入的邊一點使他們構成一個
迴路。迴路的總數相當於上一個迴路的數量的2倍+1(eg:原來的a,b和所有的其他節點構成ans條迴路,新建的
(2)a,b和所有節點構成ans條路,且新舊a,b之間新建一條迴路。)
如果插入的a,b不在一個集合,就建立a,b之間的聯繫。
#include<iostream>
#include<cstdio>
using namespace std;
#define MOD 1e9+9
const int maxn = 100010;
int a[maxn],n;
int f(int x)
{
if(x==a[x]) return a[x];
else a[x]=f(a[x]);
return a[x];
}
void Init()
{
for(int i=1;i<=n;i++) a[i]=i;
}
int main(void)
{
int m,i,ans=0,x,y;
cin>>n>>m;
Init();
for(i=1;i<=m;i++)
{
cin>>x>>y;
int t1=f(x),t2=f(y);
if(t1==t2) ans=ans*2+1;
else a[t2]=t1;
cout<<ans<<endl;
}
//for(i=1;i<=n;i++) cout<<a[i]<<" ";
return 0;
}