跳到正文

个人记录

7.20

LLC6858约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年7月20日
收录
2025年12月12日
更新
2026年11月15日
篇幅
约 5 分钟

版本

  1. v1当前

P1135 奇怪的电梯

题意:从第i层可以上到第k[i]层即可视为i与k[i]有道路 连接,可构成一个无向连通图

思路:先将没有越界的数据建图,再从A开始广搜(以为是求最短路),再记录步数即可

C++
#include<bits/stdc++.h>
using namespace std;
int n,A,B;
int k;
vector<int> a[205];
bool vis[205];
struct node{
	int u,step;
};
void bfs(){//求最短路故用广搜
	queue <node> q;
	q.push({A,0});//记录起点
	while(q.size()){
		node f = q.front();
		q.pop();
		if(f.u == B){
			cout << f.step;
			return ;
		}	
		for(int i = 0;i < a[f.u].size();i++){
			int v = a[f.u][i];
			if(vis[v] == 1) continue;
			vis[v] = 1;	
			q.push({v,f.step + 1});
		}		
	}
	cout << -1;
}
int main(){
	cin >> n >> A >> B;
	for(int i = 1;i <= n;i++){
		cin >> k;
		if(i - k >= 1) a[i].push_back(i - k);//防止越界
		if(i + k <= n) a[i].push_back(i + k);
	}
	vis[A] = 1;
	bfs();
	return 0;
}

P5663 [CSP-J2019] 加工零

题意:如果一个工人要生产L阶段的零件,那么和他相邻的工人要生产L-1阶段的,隔两个单位的要生产L-2阶段的。。。以此类推

分析:根据题意,1走到a要走L步,求出1距离a奇数步的最短路径和距离a偶数步的最短路径,如果L是奇数,就输出一到a的奇数最短路,偶数输出1到a的偶数最短路

C++
#include<bits/stdc++.h>
using namespace std;
int n,m,q;
int x,y,a,l;
int dis1[100005],dis2[100005];//奇数最短路和偶数最短路 
vector<int> g[100005];
struct node{
	int x,step;
};
void bfs(){ 
	memset(dis1,0x3f,sizeof dis1);
	memset(dis2,0x3f,sizeof dis2);
	queue <node> q;//记录步数 
	q.push({1,0});
	while(q.size()){
		node f = q.front();
		q.pop();
		for(int i = 0;i < g[f.x].size();i++){
				int v = g[f.x][i];//f.step是从1到v的路径 
			
			if((f.step + 1) % 2 == 1){
				if(f.step + 1 < dis1[v]) dis1[v] = f.step + 1,q.push({v,f.step + 1});
				
			}else{
				if(f.step + 1 < dis2[v]) dis2[v] = f.step + 1,q.push({v,f.step + 1});
	
			}
		}
	}
}
int main(){
	cin >> n >> m >> q; 
	for(int i = 1;i <= m;i++){
		cin >> x >> y; 
		g[x].push_back(y);
		g[y].push_back(x);
		
	}
	bfs();
	while(q--){
		cin >> a >> l;//从1能不能刚好走L步到a
		bool f = 0;
		if(l % 2 == 1){
			if(dis1[a] > l) cout << "No";
			else cout << "Yes";
		}else{
			if(dis2[a] > l) cout << "No";
			else cout << "Yes";
		}

		cout << '\n'; 
	}
	return 0;
}

```cpp
#include<bits/stdc++.h>
using namespace std;
long long n;
long long m,size2;

vector <int> a[100005];

int main(){
	cin >> n >> m;
	for(int i = 1,x, y;i <= m;i++){
		cin >> x >> y;
		if(x == y or find(a[x].begin(),a[x].end(),y) != a[x].end()) continue;//
		a[x].push_back(y);
		a[y].push_back(x); 
	}
	long long size1 = 0;
	for(int i = 1;i <= n;i++){
		if(a[i].size() == 1) size1++;
		if(a[i].size() == 2) size2++; 
	}

	if(size1 == n - 1) cout << "star topology";
	else if(size1 == 2 and size2 == n - 2) cout << "bus topology"; 
	else if(size2 == n) cout << "ring topology";
	else cout << "unknown topology";	
	return 0;
}
代码
原文