Luogu P13017 [GESP202506 七级] 线图 题解 [ 黄 ] [ 图论 ] [ 组合数学 ]
线图:树的遍历,但是只要统计边数。感觉 P13017 和 P13020 都是从 P11363 里拆出来弱化的。
注意到线图中一条边存在,当且仅当两个端点所代表的边在原图中有一个共同的端点。
于是以原图中的节点计数,对每个点找任意与它相连的两条边在线图中相连,该节点贡献的边的总数显然是 \(C_{d_u}^2=\dfrac{d_u(d_u-1)}{2}\),其中 \(d_u\) 表示点 \(u\) 在原图中的度数。最后将原图中所有节点贡献的边数相加即为答案。
时间复杂度 \(O(n)\)。
#include <bits/stdc++.h>
#define fi first
#define se second
#define eb(x) emplace_back(x)
#define pb(x) push_back(x)
#define lc(x) (tr[x].ls)
#define rc(x) (tr[x].rs)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef long double ldb;
using pi=pair<int,int>;
const int N=100005;
ll n,m,ans=0,d[N];
int main()
{
//freopen("sample.in","r",stdin);
//freopen("sample.out","w",stdout);
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n>>m;
while(m--)
{
int u,v;
cin>>u>>v;
d[u]++;d[v]++;
}
for(int i=1;i<=n;i++)ans+=d[i]*(d[i]-1)/2;
cout<<ans;
return 0;
}

浙公网安备 33010602011771号