This commit is contained in:
Caikecheng
2025-10-13 19:53:00 +08:00
53 changed files with 1360 additions and 129620 deletions

View File

@@ -0,0 +1,133 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- 你的其他样式 -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
MathJax.config = {
tex: {
inlineMath: [['$', '$'], ['\(', '\)']]
},
svg: {
fontCache: 'global'
}
};
</script>
</head>
<body>
<h1>效率的重要性与实践验证</h1>
<h2>效率</h2>
<h3>理论热身:算法选择的智慧</h3>
<h4>任务:分析与决策</h4>
<p>项目组目前有两套备选的交通信号灯同步算法,它们将在不同性能的服务器上运行:</p>
<ul>
<li>
<p><strong>方案A</strong>部署在超级服务器上10^9 次运算/秒采用的是一种较为简单的算法处理n个路口需要 <eq>2n^2</eq> 次计算。</p>
</li>
<li>
<p><strong>方案B</strong>部署在普通服务器上10^7 次运算/秒但采用的是一种更优化的算法处理n个路口需要 <eq>50nlog_2n</eq> 次计算。</p>
</li>
</ul>
<p>你的项目经理右侧的Agent希望你通过分析来判断哪个方案更具前景。请与TA对话逐一回答以下问题。</p>
<h4>思考题</h4>
<p>与右侧的Agent对话回答以下问题</p>
<ol>
<li>
<p><strong>概念回顾</strong>:首先,请向你的“经理”解释,根据课程所学,一个合格的“算法”应具备哪些基本特征?</p>
</li>
<li>
<p><strong>小规模测试</strong>对于一个包含100个路口的小型城区n=100计算并说明方案A和方案B分别需要多长时间完成计算在这种情况下你会推荐哪个方案</p>
</li>
<li>
<p><strong>大规模应用</strong>现在我们需要为一座拥有100万个路口的大都市n=1,000,000进行规划。再次计算并说明两个方案的耗时。你的推荐会改变吗为什么</p>
</li>
<li>
<p><strong>总结陈词</strong>:综合以上分析,向你的“经理”总结:为什么一个更优的算法设计,其重要性远超硬件性能的提升? 这验证了课程中提到的哪个核心观点?</p>
</li>
</ol>
<h3>编程实践:验证算法的真实性能</h3>
<h4>任务:编码与分析</h4>
<p>理论分析让你认识到了算法效率的重要性。现在,你需要通过编程来亲身感受不同交通状况对同一算法性能的巨大影响。我们将以“插入排序”为例,来处理三种典型的交通流量数据,这分别对应算法分析中的<strong>最好</strong><strong>最坏</strong><strong>平均</strong>情况。</p>
<h5>题目:模拟交通流量排序</h5>
<p>实现插入排序算法,并验证其在处理“畅通无阻”(数据有序)、“交通大堵塞”(数据逆序)和“随机车流”(数据随机)三种模式时的效率差异。</p>
<h5>代码框架</h5>
<p>在代码编辑区,完成 <code>insertion_sort(arr)</code> 函数的实现后运行完整代码并与Agent讨论结果。
<strong>请创建任意文件,将下面代码写入到编辑器中</strong></p>
<pre><code class="language-python">import random
import time
def insertion_sort(arr):
&quot;&quot;&quot;
实现插入排序算法
参数arr: 待排序的交通数据数组(整数代表车辆通行次序)
返回: 排序后的数组
&quot;&quot;&quot;
# TODO: 请在此处实现你的插入排序逻辑
def generate_traffic_data(n):
&quot;&quot;&quot;
生成模拟交通数据
参数n: 数据规模(路口数量或监控点数量)
返回: 三种不同交通状况的数据
&quot;&quot;&quot;
random_data = [random.randint(0, 10**6) for _ in range(n)]
# 模拟“畅通无阻”:交通流按次序进入,数据基本有序 (Best Case)
best_case_data = sorted(random_data)
# 模拟“交通大堵塞”:疏散时情况完全反转,数据逆序 (Worst Case)
worst_case_data = sorted(random_data, reverse=True)
# 模拟“随机车流”:正常但无规律的交通状况 (Average Case)
average_case_data = random_data
return best_case_data, worst_case_data, average_case_data
def measure_performance(func, data):
&quot;&quot;&quot;
测量算法性能
参数func: 排序函数
参数data: 交通数据
返回: 执行时间(毫秒)
&quot;&quot;&quot;
start_time = time.perf_counter_ns()
func(data.copy()) # 使用副本避免影响其他测试
end_time = time.perf_counter_ns()
return (end_time - start_time) / 10**6 # 转换为毫秒
#测试不同规模的路口网络
network_sizes = [1000, 5000, 10000]
print(&quot;交通数据处理算法性能测试:&quot;)
for size in network_sizes:
best, worst, avg = generate_traffic_data(size)
time_best = measure_performance(insertion_sort, best)
time_worst = measure_performance(insertion_sort, worst)
time_avg = measure_performance(insertion_sort, avg)
print(f&quot;网络规模 n={size}:&quot;)
print(f&quot; - 畅通无阻 (Best Case): {time_best:.2f} ms&quot;)
print(f&quot; - 交通大堵塞 (Worst Case): {time_worst:.2f} ms&quot;)
print(f&quot; - 随机车流 (Average Case): {time_avg:.2f} ms&quot;)
</code></pre>
<h4>分析与讨论</h4>
<p>完成编程并得到输出后请与右侧Agent讨论以下问题以检验你的理解</p>
<ol>
<li>
<p><strong>结果分析</strong>当网络规模从1000增加到10000时“交通大堵塞”最坏情况的处理时间增长了大约多少倍这更符合O(n)线性还是O(n2)(二次)的增长模式?</p>
</li>
<li>
<p><strong>原因探究</strong>:为什么“畅通无阻”(最好情况)的处理速度如此之快?它的时间复杂度是什么?请结合你的代码逻辑来解释。</p>
</li>
<li>
<p><strong>实践应用</strong>:根据你的实验结果,你认为插入排序是否适合用于需要快速响应大规模交通拥堵的实时预警系统?为什么?</p>
</li>
<li>
<p><strong>融会贯通</strong>:结合第一关的理论分析和第二关的编程实验,你对“算法是解决问题的核心”这句话有了怎样更深的理解?</p>
</li>
</ol>
</body>
</html>

View File

@@ -0,0 +1,116 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- 你的其他样式 -->
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
MathJax.config = {
tex: {
inlineMath: [['$', '$'], ['\(', '\)']]
},
svg: {
fontCache: 'global'
}
};
</script>
</head>
<body>
<h1>分治策略进阶与主方法</h1>
<blockquote>
<p>Auto-generated at 2025-09-22 15:44</p>
</blockquote>
<h2>分治策略进阶与主方法</h2>
<h3>第一关:理论学习:主方法 (Master Theorem)</h3>
<h4>任务:掌握主方法</h4>
<h5>场景介绍</h5>
<p>在分析归并排序时,我们通过递推关系<eq>T(n)=2T(n/2)+Θ(n)</eq>得出了 O(nlogn) 的结论。但每次都画递归树很繁琐。主方法为形如 T(n)=aT(n/b)+f(n) 的递推式提供了一个“公式化”的求解捷径。</p>
<h5>思考题</h5>
<p>请与右侧的Agent你的项目经理对话学习并应用主方法</p>
<ol>
<li>
<p><strong>回顾与识别</strong>:对于归并排序的递推式 <eq>T(n)=2T(n/2)+Θ(n)</eq>,请指出主方法公式中对应的 <code>a</code><code>b</code><code>f(n)</code> 分别是什么?</p>
</li>
<li>
<p><strong>核心比较</strong>:主方法的核心是比较 <code>f(n)</code><eq>nlog_ba</eq> 的大小。请计算出归并排序中<eq>nlog_ba</eq> 的值,并判断它与 <code>f(n)</code> 的关系符合主方法的哪种情况Case</p>
</li>
<li>
<p><strong>实战演练</strong>:现在,运用你学到的主方法,求解以下几种在算法分析中常见的递推式,并说明你分别应用了主方法的哪种情况。</p>
<ul>
<li>a. <eq>T(n)=2T(n/4)+\sqrt n</eq></li>
<li>b.<eq>T(n)=7T(n/2)+n^2</eq> (这是Strassen矩阵乘法算法的复杂度模型)</li>
<li>c. <eq>T(n)=7T(n/3)+n^2</eq></li>
</ul>
</li>
</ol>
<h3>第二关:编程实践:最大子数组问题</h3>
<h4>任务:编码与分析</h4>
<h5>场景介绍</h5>
<p>我们的任务是分析每日交通流量的<strong>变化数组</strong>(正数代表流量增加,负数代表减少),并找到哪一个<strong>连续时段</strong>的流量总增量最大。这在算法上被称为“最大子数组问题” 6666。例如对于流量变化数组<code>[13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]</code>总增量最大的连续时段是从第8天到第11天总增量为 <code>18 + 20 - 7 + 12 = 43</code>
虽然这个问题可以通过O(n2) 的暴力法求解,但我们将使用更高效的分治策略。</p>
<h5>题目:最大交通流量增量</h5>
<p>你需要实现一个分治算法来解决最大子数组问题。同时,为了对比,你也会实现一个暴力求解算法。</p>
<h5>代码框架</h5>
<p>在下方代码编辑区,完成 <code>find_maximum_subarray</code>(分治法)和 <code>find_max_crossing_subarray</code> 以及 <code>find_maximum_subarray_brute</code>(暴力法)三个函数。</p>
<pre><code class="language-python">import time
import random
def find_maximum_subarray_brute(arr):
&quot;&quot;&quot;
使用暴力法求解最大子数组问题
返回: (最大和, 开始索引, 结束索引)
&quot;&quot;&quot;
#--- 本周任务:请在下方实现分治算法 ---
def find_max_crossing_subarray(arr, low, mid, high):
&quot;&quot;&quot;
找到跨越中点的最大子数组
返回: (最大和, 开始索引, 结束索引)
&quot;&quot;&quot;
# TODO: 实现寻找跨越中点的最大子数组的逻辑
# 提示: 从mid向左和向右分别扫描找到各自的最大和
def find_maximum_subarray(arr, low, high):
&quot;&quot;&quot;
使用分治法求解最大子数组问题
返回: (最大和, 开始索引, 结束索引)
&quot;&quot;&quot;
# TODO: 实现分治递归逻辑
# 提示: 递归基是当数组只有一个元素时
#--- 测试与对比部分 ---
traffic_changes = [13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7]
print(f&quot;交通流量变化数据: {traffic_changes}&quot;)
#使用分治法
max_sum_dc, start_dc, end_dc = find_maximum_subarray(traffic_changes, 0, len(traffic_changes) - 1)
print(f&quot;分治法结果: 最大增量 = {max_sum_dc}, 时段 = Day {start_dc} to Day {end_dc}&quot;)
#使用暴力法验证
max_sum_brute, start_brute, end_brute = find_maximum_subarray_brute(traffic_changes)
print(f&quot;暴力法结果: 最大增量 = {max_sum_brute}, 时段 = Day {start_brute} to Day {end_brute}&quot;)
#性能测试
large_data = [random.randint(-50, 50) for _ in range(2000)]
start_time = time.perf_counter()
find_maximum_subarray(large_data, 0, len(large_data) - 1)
dc_time = (time.perf_counter() - start_time) * 1000
print(f&quot;\n在 n=2000 的数据集上,分治法耗时: {dc_time:.2f} ms&quot;)
start_time = time.perf_counter()
find_maximum_subarray_brute(large_data)
brute_time = (time.perf_counter() - start_time) * 1000
print(f&quot;在 n=2000 的数据集上,暴力法耗时: {brute_time:.2f} ms&quot;)</code></pre>
</body>
</html>

View File

@@ -7,7 +7,9 @@
display: flex;
flex-direction: column; /* 使子元素垂直排列 */
}
#leftSidebar {
padding-left: 3px;
}
body {
font-family: Arial, sans-serif;
display: flex;

View File

@@ -30,7 +30,8 @@ body {
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
width: 100%;
max-width: 500px;
min-width: 400px;
max-width: 600px;
text-align: center;
}

View File

@@ -0,0 +1,69 @@
.username-group { position: relative; }
.field-tip {
position: absolute;
top: 40%;
left: calc(60% + 10px); /* 紧挨输入框右侧 */
transform: translateY(-50%);
width: 260px;
background: #fff;
border: 1px solid #e5e7eb;
border-radius: 8px;
box-shadow: 0 8px 24px rgba(0,0,0,0.08);
padding: 10px 12px;
font-size: 12px;
line-height: 1.5;
color: #111827;
/* 初始隐藏 */
opacity: 0;
visibility: hidden;
pointer-events: none;
transition: opacity .15s ease, visibility .15s ease;
z-index: 10;
}
.field-tip::after { /* 小三角箭头 */
content: "";
position: absolute;
top: 50%;
left: -6px;
transform: translateY(-50%);
border-width: 6px;
border-style: solid;
border-color: transparent #e5e7eb transparent transparent;
}
.field-tip::before { /* 箭头内层白色 */
content: "";
position: absolute;
top: 50%;
left: -5px;
transform: translateY(-50%);
border-width: 5px;
border-style: solid;
border-color: transparent #fff transparent transparent;
z-index: 1;
}
.field-tip strong { display: block; margin-bottom: 6px; }
.field-tip ul { margin: 0; padding-left: 16px; }
.field-tip li { margin: 2px 0; color: #374151; }
.field-tip span { font-weight: 600; color: #111827; }
/* 显示状态 */
.field-tip.is-visible {
opacity: 1;
visibility: visible;
}
/* 小屏时把提示框放到输入框下方,避免遮挡 */
@media (max-width: 640px) {
.field-tip {
top: calc(60% + 8px);
left: 0;
transform: none;
width: min(92vw, 320px);
}
.field-tip::after,
.field-tip::before {
display: none;
}
}

View File

@@ -12,8 +12,10 @@ document.addEventListener('DOMContentLoaded', function () {
});
socket.on('connect', function () {
console.log('Connected to server');
socket.emit('login', JSON.stringify(data));
OpenIframe();
socket.emit('login',JSON.stringify(data));
});
socket.on('open-iframe', function(data) {
OpenIframe();
});
// 监听来自服务器的消息
socket.on('message', function (data) {
@@ -24,29 +26,18 @@ document.addEventListener('DOMContentLoaded', function () {
// 滚动到最新消息
document.getElementById('chatbox').scrollTop = document.getElementById('chatbox').scrollHeight;
});
//监听来自服务器的消息
/*socket.on('VoiceMessage', function(data) {
console.log("Received voice answer message:", data);
socket.on('message-hint', function(data){
console.log('get message-hint');
// 显示服务器的回复消息
const VoiceMessage = document.createElement('div');
VoiceMessage.className = 'chat-message server-message';
VoiceMessage.innerHTML = `
<div><b>华实君:</b></div>
${marked.parse(data)}
`;
//插入与滚动
document.getElementById('chatbox').appendChild(VoiceMessage);
const serverMessage = document.createElement('div');
serverMessage.innerHTML = `<div id="hint-title"><b>提示</b></div><div id="hint-message" class="chat-message server-message"> ${data}</div>`;
document.getElementById('chatbox').appendChild(serverMessage);
// 滚动到最新消息
document.getElementById('chatbox').scrollTop = document.getElementById('chatbox').scrollHeight;
});*/
//监听来自服务器的语音识别消息
socket.on('VoiceMessage', function (data) {
console.log("Received voice message I sent from server:", data);
//将语音转文字显示在输入框中
document.getElementById('messageInput').value = data;
});
socket.on('request_function', function (data) {
socket.on('request_function', function(data){
try {
console.log("request_function", data);
if (typeof data === 'string') {

View File

@@ -22,7 +22,6 @@ function show_user_data(user_data, course_brief_data_list){
}
}
function openCourseProgress(courseId) {
console.log(courseId)
const course = courseData[courseId];
if (!course) return;
fetch(`/dashboard/get_course_progress`, {
@@ -33,7 +32,7 @@ function openCourseProgress(courseId) {
body: JSON.stringify({course_id: courseId})
}).then(response => response.json())
.then(data => {
console.log(data)
// console.log(data)
/*
course_last_study_date: "2025-09-06"
course_put_in_date: "2025-09-06"
@@ -75,31 +74,36 @@ function openCourseProgress(courseId) {
const subChapterItem = document.createElement('li');//课时层级
subChapterItem.classList.add('sub-chapter-item');
subChapterItem.textContent = subChapter.lesson_name;
console.log('-------------------')
console.log(course)
// 查找学生进度
lesson_score_text_content = ""
for(let i = 0; i < course.lesson_processs.length; i++) {
if (course.lesson_processs[i][2] == subChapter.lesson_name && course.lesson_processs[i][1] == chapter.chapter_name) {//确定lesson_id对应正确
///////////////////////////////////////////
//这里之后要做lesson的各个step的进度和得分
////////////////////////////////////////////
console.log('-------------------')
console.log(course.lesson_processs[i][0])
lesson_chapters_progress = course.lesson_processs[i][0];//寻找对应的每一个章节的进度
for (let j=0; j<lesson_chapters_progress.length;j++){
chapter_progress = lesson_chapters_progress[j]
if(chapter_progress.title == subChapter){
subChapterItem.textContent += ("(已"+(chapter_progress.is_rebuttal?"申辩" : "完成")+" 得分"+ (chapter_progress.is_rebuttal?chapter_progress.rebuttal_score : chapter_progress.score) +"");
}
}
if (course.lesson_processs[i][0].length === 1) {
subChapterItem.classList.add('completed');
if (course.lesson_processs[i].length<=3){break;}
for (let j =0; j< course.lesson_processs[i][3].length;j++){
if (isObject(course.lesson_processs[i][3][j]))course.lesson_processs[i][3][j]=course.lesson_processs[i][3][j]['data']
lesson_score_text_content+=course.lesson_processs[i][3][j]+';'
}
// console.log('-------------------')
// subChapterItem.textContent +=
// console.log(course.lesson_processs[i][0])
// lesson_chapters_progress = course.lesson_processs[i][0];//寻找对应的每一个章节的进度
// for (let j=0; j<lesson_chapters_progress.length;j++){
// chapter_progress = lesson_chapters_progress[j]
// if(chapter_progress.title == subChapter){
// subChapterItem.textContent += ("(已"+(chapter_progress.is_rebuttal?"申辩" : "完成")+" 得分"+ (chapter_progress.is_rebuttal?chapter_progress.rebuttal_score : chapter_progress.score) +"");
// }
// }
// if (course.lesson_processs[i][0].length === 1) {
// subChapterItem.classList.add('completed');
// }
break;
}
}
if (lesson_score_text_content!=""){lesson_score_text_content = ' ('+lesson_score_text_content+')'}
subChapterItem.textContent+=lesson_score_text_content
// 添加点击事件跳转到学习页面
subChapterItem.addEventListener('click', () => {
const courseId = encodeURIComponent(course._id); // 对课程名称进行编码
@@ -136,3 +140,7 @@ function closeCourseProgress() {
// 关闭滑出卡片
document.getElementById('courseProgress').classList.remove('open');
}
function isObject(value) {
return Object.prototype.toString.call(value) === '[object Object]';
}

View File

@@ -8,7 +8,11 @@ document.addEventListener('DOMContentLoaded', function() {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirm-password').value;
const u = validateLinuxUsername(username);
if (!u.ok) {
alert(u.error);
return;
}
if (password !== confirmPassword) {
alert('密码和确认密码不一致');
return;
@@ -36,4 +40,36 @@ document.addEventListener('DOMContentLoaded', function() {
alert('注册失败');
});
});
});
});
// 校验 Linux 用户名
function validateLinuxUsername(name) {
// 基本字符规则:^[a-z_][a-z0-9_-]*[$]?$
const basic = /^[a-z_][a-z0-9_-]*[$]?$/;
if (typeof name !== 'string' || name.length === 0) {
return { ok: false, error: '用户名不能为空' };
}
// 长度限制(常见系统为 <= 32
if (name.length > 32) {
return { ok: false, error: '用户名长度不能超过 32 个字符' };
}
if (!basic.test(name)) {
return {
ok: false,
error:
'用户名需以小写字母或下划线开头,仅包含小写字母、数字、下划线、连字符,允许以 $ 结尾'
};
}
// 可选:避免纯数字用户名(多数系统不推荐)
if (/^[0-9]+$/.test(name)) {
return { ok: false, error: '用户名不能为纯数字' };
}
// 可选:避免使用保留名
const reserved = new Set(['root', 'daemon', 'bin', 'sys', 'sync', 'games', 'man']);
if (reserved.has(name)) {
return { ok: false, error: '该用户名为系统保留名,请更换' };
}
return { ok: true };
}

View File

@@ -0,0 +1,27 @@
(function () {
let usernameInput = document.getElementById('username');
if (!usernameInput){
usernameInput = document.getElementById('teacher-username');
}
const tip = document.getElementById('username-tip');
function showTip() {
tip.classList.add('is-visible');
tip.setAttribute('aria-hidden', 'false');
}
function hideTip() {
tip.classList.remove('is-visible');
tip.setAttribute('aria-hidden', 'true');
}
usernameInput.addEventListener('focus', showTip);
usernameInput.addEventListener('blur', hideTip);
// 当用户点击提示框自身时不影响(比如复制文本)
tip.addEventListener('mousedown', e => e.preventDefault());
// 可选:输入时也显示(防止因某些浏览器失焦导致闪烁)
usernameInput.addEventListener('input', () => {
if (document.activeElement === usernameInput) showTip();
});
})();

View File

@@ -8,7 +8,11 @@ document.addEventListener('DOMContentLoaded', function() {
const email = document.getElementById('teacher-email').value;
const password = document.getElementById('teacher-password').value;
const confirmPassword = document.getElementById('teacher-confirm-password').value;
const u = validateLinuxUsername(username);
if (!u.ok) {
alert(u.error);
return;
}
// 检查密码和确认密码是否一致
if (password !== confirmPassword) {
alert('密码和确认密码不一致');
@@ -39,3 +43,35 @@ document.addEventListener('DOMContentLoaded', function() {
});
});
});
// 校验 Linux 用户名
function validateLinuxUsername(name) {
// 基本字符规则:^[a-z_][a-z0-9_-]*[$]?$
const basic = /^[a-z_][a-z0-9_-]*[$]?$/;
if (typeof name !== 'string' || name.length === 0) {
return { ok: false, error: '用户名不能为空' };
}
// 长度限制(常见系统为 <= 32
if (name.length > 32) {
return { ok: false, error: '用户名长度不能超过 32 个字符' };
}
if (!basic.test(name)) {
return {
ok: false,
error:
'用户名需以小写字母或下划线开头,仅包含小写字母、数字、下划线、连字符,允许以 $ 结尾'
};
}
// 可选:避免纯数字用户名(多数系统不推荐)
if (/^[0-9]+$/.test(name)) {
return { ok: false, error: '用户名不能为纯数字' };
}
// 可选:避免使用保留名
const reserved = new Set(['root', 'daemon', 'bin', 'sys', 'sync', 'games', 'man']);
if (reserved.has(name)) {
return { ok: false, error: '该用户名为系统保留名,请更换' };
}
return { ok: true };
}

View File

@@ -0,0 +1,119 @@
<html>
<head>
<style>
img {
max-width: 100%;
height: auto;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
</head>
<body class="markdown-body">
<h1>效率的重要性与实践验证</h1>
<h2>效率</h2>
<h3>理论热身:算法选择的智慧</h3>
<h4>任务:分析与决策</h4>
<p>项目组目前有两套备选的交通信号灯同步算法,它们将在不同性能的服务器上运行:</p>
<ul>
<li>
<p><strong>方案A</strong>部署在超级服务器上10^9 次运算/秒采用的是一种较为简单的算法处理n个路口需要 $2n^2$ 次计算。</p>
</li>
<li>
<p><strong>方案B</strong>部署在普通服务器上10^7 次运算/秒但采用的是一种更优化的算法处理n个路口需要 $50nlog_2n$ 次计算。</p>
</li>
</ul>
<p>你的项目经理右侧的Agent希望你通过分析来判断哪个方案更具前景。请与TA对话逐一回答以下问题。</p>
<h4>思考题</h4>
<p>与右侧的Agent对话回答以下问题</p>
<ol>
<li>
<p><strong>概念回顾</strong>:首先,请向你的“经理”解释,根据课程所学,一个合格的“算法”应具备哪些基本特征? </p>
</li>
<li>
<p><strong>小规模测试</strong>对于一个包含100个路口的小型城区n=100计算并说明方案A和方案B分别需要多长时间完成计算在这种情况下你会推荐哪个方案</p>
</li>
<li>
<p><strong>大规模应用</strong>现在我们需要为一座拥有100万个路口的大都市n=1,000,000进行规划。再次计算并说明两个方案的耗时。你的推荐会改变吗为什么</p>
</li>
<li>
<p><strong>总结陈词</strong>:综合以上分析,向你的“经理”总结:为什么一个更优的算法设计,其重要性远超硬件性能的提升? 这验证了课程中提到的哪个核心观点?</p>
</li>
</ol>
<h3>编程实践:验证算法的真实性能</h3>
<h4>任务:编码与分析</h4>
<p>理论分析让你认识到了算法效率的重要性。现在,你需要通过编程来亲身感受不同交通状况对同一算法性能的巨大影响。我们将以“插入排序”为例,来处理三种典型的交通流量数据,这分别对应算法分析中的<strong>最好</strong><strong>最坏</strong><strong>平均</strong>情况。</p>
<h5>题目:模拟交通流量排序</h5>
<p>实现插入排序算法,并验证其在处理“畅通无阻”(数据有序)、“交通大堵塞”(数据逆序)和“随机车流”(数据随机)三种模式时的效率差异。</p>
<h5>代码框架</h5>
<p>在代码编辑区,完成 <code>insertion_sort(arr)</code> 函数的实现后运行完整代码并与Agent讨论结果。
<strong>请创建任意文件,将下面代码写入到编辑器中</strong>
```python
import random
import time</p>
<p>def insertion_sort(arr):
"""
实现插入排序算法
参数arr: 待排序的交通数据数组(整数代表车辆通行次序)
返回: 排序后的数组
"""
# TODO: 请在此处实现你的插入排序逻辑</p>
<p>def generate_traffic_data(n):
"""
生成模拟交通数据
参数n: 数据规模(路口数量或监控点数量)
返回: 三种不同交通状况的数据
"""
random_data = [random.randint(0, 10**6) for _ in range(n)]
# 模拟“畅通无阻”:交通流按次序进入,数据基本有序 (Best Case)
best_case_data = sorted(random_data)
# 模拟“交通大堵塞”:疏散时情况完全反转,数据逆序 (Worst Case)
worst_case_data = sorted(random_data, reverse=True)
# 模拟“随机车流”:正常但无规律的交通状况 (Average Case)
average_case_data = random_data
return best_case_data, worst_case_data, average_case_data</p>
<p>def measure_performance(func, data):
"""
测量算法性能
参数func: 排序函数
参数data: 交通数据
返回: 执行时间(毫秒)
"""
start_time = time.perf_counter_ns()
func(data.copy()) # 使用副本避免影响其他测试
end_time = time.perf_counter_ns()
return (end_time - start_time) / 10**6 # 转换为毫秒</p>
<h1>测试不同规模的路口网络</h1>
<p>network_sizes = [1000, 5000, 10000]
print("交通数据处理算法性能测试:")
for size in network_sizes:
best, worst, avg = generate_traffic_data(size)</p>
<pre><code>time_best = measure_performance(insertion_sort, best)
time_worst = measure_performance(insertion_sort, worst)
time_avg = measure_performance(insertion_sort, avg)
print(f"网络规模 n={size}:")
print(f" - 畅通无阻 (Best Case): {time_best:.2f} ms")
print(f" - 交通大堵塞 (Worst Case): {time_worst:.2f} ms")
print(f" - 随机车流 (Average Case): {time_avg:.2f} ms")
</code></pre>
<p>```</p>
<h4>分析与讨论</h4>
<p>完成编程并得到输出后请与右侧Agent讨论以下问题以检验你的理解</p>
<ol>
<li>
<p><strong>结果分析</strong>当网络规模从1000增加到10000时“交通大堵塞”最坏情况的处理时间增长了大约多少倍这更符合O(n)线性还是O(n2)(二次)的增长模式?</p>
</li>
<li>
<p><strong>原因探究</strong>:为什么“畅通无阻”(最好情况)的处理速度如此之快?它的时间复杂度是什么?请结合你的代码逻辑来解释。</p>
</li>
<li>
<p><strong>实践应用</strong>:根据你的实验结果,你认为插入排序是否适合用于需要快速响应大规模交通拥堵的实时预警系统?为什么?</p>
</li>
<li>
<p><strong>融会贯通</strong>:结合第一关的理论分析和第二关的编程实验,你对“算法是解决问题的核心”这句话有了怎样更深的理解?</p>
</li>
</ol>
</body>
</html>

View File

@@ -0,0 +1,126 @@
<html>
<head>
<style>
img {
max-width: 100%;
height: auto;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/5.2.0/github-markdown.min.css">
</head>
<body class="markdown-body">
<h1>算法设计范式:分而治之与归并排序</h1>
<blockquote>
<p>Auto-generated at 2025-09-22 15:38</p>
</blockquote>
<h2>算法设计范式:分而治之与归并排序</h2>
<h3>第一关:理论探究:分而治之的力量</h3>
<p><strong>案例背景:智慧城市交通优化系统</strong></p>
<p>在上周的工作中你已经实现并分析了插入排序在交通数据处理中的性能。虽然它在数据量较小或基本有序的情况下表现不错但在应对大规模拥堵逆序数据其性能瓶颈非常明显。本周你的项目经理Agent将向你介绍一种更高效的算法设计思想——“分而治之”并要求你掌握其代表算法归并排序。</p>
<h4>任务:理解与分析</h4>
<h5>场景介绍</h5>
<p>你的经理告诉你归并排序Merge Sort是解决大规模排序问题的利器。在投入编码之前你必须先从理论上理解它为何如此高效。</p>
<h5>思考题</h5>
<p>请与右侧的Agent你的项目经理对话清晰地回答以下问题以证明你已理解核心思想</p>
<ol>
<li>
<p><strong>分治思想</strong>根据课程资料请解释什么是“分而治之”Divide-and-Conquer设计范式它包含哪三个基本步骤</p>
</li>
<li>
<p><strong>递推关系</strong>:归并排序的时间复杂度可以用递推式 T(n)=2T(n/2)+Θ(n) 来表示。请解释这个式子各部分的含义:</p>
<ul>
<li><code>2</code> 代表什么?</li>
<li><code>T(n/2)</code> 代表什么?</li>
<li><code>Θ(n)</code> 代表什么?</li>
</ul>
</li>
<li>
<p><strong>效率对比</strong>你的同事认为插入排序经过极致优化后处理n个数据的耗时为 $0.1n^2$;而归并排序由于递归和合并开销,耗时为 1000nlog_2n。在处理超大规模城市交通数据时即n趋于无穷大时哪个算法最终会胜出请从渐进增长的角度解释你的理由。</p>
</li>
<li>
<p><strong>增长排序</strong>:将下列函数的渐进增长率从低到高排序,并将它们划分到等价类(即 Θ 关系相同的函数)。这有助于你理解不同算法效率的所在层级。 </p>
<ul>
<li>$n^2$ (插入排序最坏情况)</li>
<li>nlogn (归并排序)</li>
<li>n (一种非常低效的蛮力算法)</li>
<li>$2^n$ (另一种指数级算法)</li>
<li>logn (类似二分查找的效率)</li>
</ul>
</li>
</ol>
<h3>第二关:编程实践:实现归并排序</h3>
<h4>任务:编码与对比</h4>
<h5>场景介绍</h5>
<p>现在你已经从理论上理解了归并排序的威力。是时候亲手实现它,并与上周的插入排序进行一次性能上的正面较量了!</p>
<h5>题目:实现归并排序并对比性能</h5>
<p>你需要实现归并排序的核心函数,并利用上周的测试框架来直观对比它与插入排序在处理不同交通数据时的表现。</p>
<h5>代码框架</h5>
<p>在下方代码编辑区,完成 <code>merge_sort(arr)</code><code>merge(left, right)</code> 两个函数的实现。
```python
import random
import time</p>
<h1>上周实现的插入排序(用于对比)</h1>
<p>def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j &gt;= 0 and arr[j] &gt; key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr</p>
<h1>--- 本周任务:请在下方实现归并排序 ---</h1>
<p>def merge_sort(arr):
"""
实现归并排序算法
参数arr: 待排序的交通数据数组
返回: 一个新的、排序好的数组
"""
# TODO: 实现归并排序的递归逻辑
# 提示当数组元素个数小于等于1时递归终止</p>
<p>def merge(left, right):
"""
合并两个已排序的子数组
参数left: 左侧已排序数组
参数right: 右侧已排序数组
返回: 合并后的一个有序数组
"""</p>
<h1>--- 测试与对比部分 ---</h1>
<p>def measure_performance(sort_func, data):
start_time = time.perf_counter_ns()
sort_func(data.copy())
end_time = time.perf_counter_ns()
return (end_time - start_time) / 10**6</p>
<p>network_sizes = [1000, 5000, 10000, 50000]
print("算法性能对比测试:")
for size in network_sizes:
# 生成逆序数据,这是插入排序的最坏情况
worst_case_data = list(range(size, 0, -1))</p>
<pre><code>time_insertion = measure_performance(insertion_sort, worst_case_data)
time_merge = measure_performance(merge_sort, worst_case_data)
print(f"--- 网络规模 n={size} (最坏情况) ---")
print(f" - 插入排序: {time_insertion:.2f} ms")
print(f" - 归并排序: {time_merge:.2f} ms")
</code></pre>
<p>```</p>
<h5>分析与讨论</h5>
<p>完成编程并得到输出后请与右侧Agent讨论以下问题</p>
<ol>
<li>
<p><strong>性能验证</strong>:观察“交通大堵塞”(最坏情况)的测试结果,归并排序的性能表现与插入排序有何天壤之别?这是否验证了你在第一关的理论分析?</p>
</li>
<li>
<p><strong>性能稳定性</strong>:如果我们将测试数据换成“畅通无阻”(最好情况)或“随机车流”(平均情况),你认为归并排序的运行时间会发生巨大变化吗?为什么?</p>
</li>
<li>
<p><strong>空间成本</strong>:在实现 <code>merge</code> 函数时,你可能创建了一个新的数组 <code>merged</code> 来存放结果。这在算法分析中被称为“空间复杂度”。与在原数组上进行交换的插入排序相比,归并排序的这个特点是优点还是缺点?</p>
</li>
<li>
<p><strong>最终决策</strong>:作为项目工程师,你会选择哪种排序算法用于我们的大规模交通调度系统?请综合考虑<strong>时间效率</strong><strong>空间成本</strong>来陈述你的理由。</p>
</li>
</ol>
</body>
</html>