-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMetrograph.cpp
More file actions
98 lines (95 loc) · 3 KB
/
Metrograph.cpp
File metadata and controls
98 lines (95 loc) · 3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "Metrograph.hpp"
MetroGraph::MetroGraph(){}
MetroGraph::~MetroGraph() {
for (auto* q : queues) {
if (q) delete q;
}
}
//给输入的地铁站赋予ID,FIFO
int MetroGraph::CreateID(const std::string& name){
if (nmtonum.count(name)) return nmtonum[name];
else{
int NewID = nmtonum.size();
nmtonum[name] = NewID;
numtonm[NewID] = name;
adj.resize(NewID + 1);
return NewID;
}
}
//加边
void MetroGraph::AddEdge(int u,int v,int line,double time,double dist,int crowd){
//因为地铁线路是无向图,所以两边都要加~
adj[u].emplace_back(v,line,time,dist,crowd);
adj[v].emplace_back(u,line,time,dist,crowd);
}
//返回整张图
const std::vector<std::vector<Edge>>& MetroGraph::GetAdj() const{
return adj;
}
//查询操作:给定地铁站名称返回ID
int MetroGraph::GetID(const std::string& name){
if (nmtonum.count(name)) return nmtonum[name];
else return -1;
}
//查询操作:给定地铁站ID返回名称
std::string MetroGraph::GetName(int id){
if (numtonm.count(id)) return numtonm[id];
else return "此站点未收录";
}
int MetroGraph::GetTotalStation() const{
return adj.size();
}
//从文件里导入图
bool MetroGraph::LoadGraph(const std::string& file){
std::ifstream fin(file);
if (!fin){
std::cout << "找不到文件" << "\n";
return 0;
}
std::string s1,s2;int line,crowd;double time,dist;
while (fin >> s1 >> s2 >> line >> dist >> time >> crowd){
int u = CreateID(s1);
int v = CreateID(s2);
AddEdge(u,v,line,time,dist,crowd);
}
fin.close(); return true;
}
//模拟生成未来 30 分钟数据
void MetroGraph::SimulateFlow() {
srand((unsigned)time(NULL));
int n = GetTotalStation();
queues.resize(n);
for(int i=0; i<n; i++) {
if(!queues[i]) queues[i] = new FlowQueue();
else queues[i]->clear();
// 随机生成 1-30 分钟的人数 (0-200人)
for(int t = 1; t <= 30; ++t) {
queues[i]->push(t, rand() % 200);//随机数生成器
}
}
std::cout << "已完成未来 30 分钟客流预测模拟。\n";
}
//用优先队列找最挤的站
void MetroGraph::PrintCrowdTopK(int time, int k) {
std::priority_queue<StationCrowd> pq;
for(int i=0; i<GetTotalStation(); i++) {
if(queues[i]) {
int num = queues[i]->get_count(time);
if(num > 0) pq.push({i, num});
}
}
std::cout << "\n第 " << time << " 分钟拥挤度 Top-" << k << ":\n";
for(int i=0; i<k && !pq.empty(); i++) {
StationCrowd top = pq.top(); pq.pop();
std::cout << " " << GetName(top.id) << " (" << top.num << "人)\n";
}
}
//异常处理:把线路的 closed 属性改掉
void MetroGraph::SetLineStatus(int line_id, bool open) {
for(auto& list : adj) {
for(auto& edge : list) {
if(edge.line == line_id) edge.closed = !open;
}
}
std::cout << " 线路 " << line_id << (open ? " 已恢复" : " 已停运") << "\n";
}