跳到正文

个人记录

7.17暑假课程-图论

bailuoboyu约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月17日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 4 分钟

版本

  1. v1当前

家庭作业

B3613 图的存储与出边的排序

AC代码

C++
#include <bits/stdc++.h>
using namespace std;
long long t,n,m,u,v;
vector<unsigned long long int> w[500010];
int main() {
    std::ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>t;
    while(t--){
        cin>>n>>m;
        for(long long i=1;i<=n;i++){
            w[i].clear();
        }
        for (long long i=1;i<=m;i++){
            cin>>u>>v;
            w[u].push_back(v);
        }
        for (long long i=1; i<=n;i++){
            sort(w[i].begin(),w[i].end());
            for (auto v:w[i]) {
                cout<<v<<' ';
            }
            cout<<'\n';
        }
    }
    return 0;
}

U460102 点的邻居

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
const int MAXN=200010;
long long n,m;
set<long long>a[MAXN];

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    for(long long i = 1, x, y; i <= m; i++) {
        cin >> x >> y;
        if(x != y) {
            a[x].insert(y);
            a[y].insert(x);
        }
    }
    
    for(long long i = 1; i <= n; i++) {
        for(auto it = a[i].begin(); it != a[i].end(); it++) {
            cout << *it << ' ';
        }
        cout << '\n';
    }
    
    return 0;
}

B4292 [蓝桥杯青少年组省赛 2022] 路线

AC代码

C++
#include<bits/stdc++.h>
using namespace std;
long long n,m,ans[110];
bool vis[110];
vector<long long> mp[110];
void bfs(){
	queue<long long> q;
	q.push(n);
	long long tmp;
	while(!q.empty()){
		tmp=q.front();
		vis[tmp]=1;
		q.pop(); 
		for(int i=0;i<mp[tmp].size();i++){
			if(!vis[mp[tmp][i]]){
				q.push(mp[tmp][i]);
				vis[mp[tmp][i]]=1;
				ans[mp[tmp][i]]=ans[tmp]+1;
			}
		}
	} 
} 
int main(){
	cin>>n>>m;
	for(long long i=1,x,y;i<=m;i++){
		cin>>x>>y;
		mp[x].push_back(y);
		mp[y].push_back(x);
	}
	bfs();
	for(long long i=1;i<n;i++){
		if(ans[i]==0){
			cout<<-1<<' ';
			continue; 
		}
		cout<<ans[i]<< ' ';
	}
	return 0;
}
原文