Codeforces - 1133F1 (vector代替邻接表存图)
题目链接:http://codeforces.com/problemset/problem/1133/F1
题意:n个点m条无向边,求一个最大度数尽可能大的生成树。n是2e5的
思路 :选择度数最大的点,bfs跑一边把边输出就好了。
注:因为n是2e5的,所以不能用二维数组存图,用邻接表存有不太会,这里学到了一个新方法,用vector存。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
vector <int> a[maxn]; // vector存图
int via[maxn];
int n,m;
void bfs( int v0 )
{
memset(via,0,sizeof(via));
queue <int> Q;
Q.push(v0);
via[v0] = 1;
while ( !Q.empty() ) {
int t = Q.front();
Q.pop();
for ( int i=0; i<a[t].size(); i++ ) { // 找与t相连的点
if ( via[a[t][i]]==0 ) {
via[a[t][i]] = 1; // 输出符合条件的两个点,代表边
Q.push(a[t][i]);
}
}
}
}
int main()
{
int x,y;
cin >> n >> m;
for ( int i=0; i<m; i++ ) {
cin >> x >> y;
a[x].push_back(y); // vector存无向图
a[y].push_back(x); //
}
int pos = 0;
int v = 0;
for ( int i=1; i<=n; i++ ) { // 找度数最大的点
if ( a[i].size()>pos ) {
pos = a[i].size();
v = i;
}
}
bfs(v);
return 0;
}