hd_Security Center

本文介绍了一个使用C++实现的图遍历算法示例,包括图的创建、广度优先搜索(BFS)等核心功能。通过具体的代码示例展示了如何在给定节点集合中进行有效遍历,并特别关注了病毒传播模拟场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream> #include <queue> using namespace std; const int SIZE = 20005; int hash[SIZE]; int n, e, c; int anti[SIZE]; int virus; struct EdgeNode { int adjvex; struct EdgeNode* next; }; struct VexNode { int adjvex; EdgeNode* firstArc; }; struct Gragh { int n, e; VexNode adjvexList[SIZE]; }; void Create(Gragh* & g) { int b, t; EdgeNode* p, * q; g = new Gragh; g->n = n; g->e = e; for(int i=0; i<g->n; ++i) { g->adjvexList[i].adjvex = i; g->adjvexList[i].firstArc = NULL; } for(int i=0; i<g->e; ++i) { cin>>b>>t; p = new EdgeNode; p->adjvex = t; p->next = g->adjvexList[b].firstArc; g->adjvexList[b].firstArc = p; q = new EdgeNode; q->adjvex = b; q->next = g->adjvexList[t].firstArc; g->adjvexList[t].firstArc = q; } } /* void Display(Gragh* & g) { cout<<"+++++++++++++"<<endl; EdgeNode* p; for(int i=0; i<g->n; ++i) { cout<<i<<"->"; p = g->adjvexList[i].firstArc; while(p != NULL) { cout<<p->adjvex<<"->"; p = p->next; } cout<<"^"<<endl; } cout<<"~~~~~~~~~~~~~"<<endl; } */ bool isAnti(int a) { for(int i=0; i<c; ++i) { if(anti[i] == a) return 1; } return 0; } void bfs(Gragh* &g) { queue <int > q; int start, cur; start = virus; q.push(start); while(!q.empty()) { cur = q.front(); q.pop(); hash[cur] = -1; EdgeNode* p = g->adjvexList[cur].firstArc; while(p != NULL) { if(isAnti(p->adjvex) || hash[p->adjvex] == -1){ p = p->next; continue; } else { q.push(p->adjvex); p = p->next; } } } for(int i=0; i<c; ++i) { queue <int> q; int start, cur; start = anti[i]; q.push(start); while(!q.empty()) { cur = q.front(); q.pop(); // visited[cur] = 1; hash[cur] = 1; EdgeNode* p = g->adjvexList[cur].firstArc; while(p != NULL) { // if(!visited[p->adjvex]) if(p->adjvex == virus || hash[p->adjvex] == 1){ p = p->next; continue; } else { q.push(p->adjvex); p = p->next; } } } } } int main() { int t; cin>>t; while(t--) { memset(hash,0,sizeof(hash)); int cnt=0; cin>>n>>e>>c; cin>>virus; for(int i=0; i<c; ++i) { cin>>anti[i]; } Gragh* g; Create(g); //Display(g); bfs(g); for(int i=0; i<n; ++i) { if(hash[i] == -1) cnt++; } cout<<cnt-1<<endl; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值