1 / 12

1-5 防守阵地

1-5 防守阵地. 学号: 130321034 姓名:张志强. 问题描述. 部队中有 N 个士兵,每个士兵有各自的能力指数 Xi ,在一次演练中,指挥部确定了 M 个需要防守的地点,按重要程度从低到高排序,依次以数字 1 到 M 标注每个地点的重要程度,指挥部将选择 M 个士兵依次进入指定地点进行防守任务,能力指数为 X 的士兵防守重要程度为 Y 的地点将得到 X*Y 的参考指数。现在士兵们排成一排,请你选择出连续的 M 个士兵依次参加防守,使得总的参考指数最大。. 对问题的理解和分析.

Télécharger la présentation

1-5 防守阵地

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 1-5 防守阵地 学号:130321034 姓名:张志强

  2. 问题描述 • 部队中有N个士兵,每个士兵有各自的能力指数Xi,在一次演练中,指挥部确定了M个需要防守的地点,按重要程度从低到高排序,依次以数字1到M标注每个地点的重要程度,指挥部将选择M个士兵依次进入指定地点进行防守任务,能力指数为X的士兵防守重要程度为Y的地点将得到X*Y的参考指数。现在士兵们排成一排,请你选择出连续的M个士兵依次参加防守,使得总的参考指数最大。

  3. 对问题的理解和分析 • 假设有士兵X1、X2、X3、X4、X5、X6、X7…..Xn进行守阵地M个,则参考指数有 X1+2X2+3X3+…+MXm , X2+2X3+3X4+…+MXm+1, X3+2X4+3X5+…+MXm+2,... 结果即为此几项中的最大值。 按照一般解法,需每次进行和计算,在大数据下程序将超时。因此程序优化只能从减少计算加法及乘法次数下手。

  4. 对问题的理解和分析 仔细观察相邻两项间差值,发现 X2+2X3+3X4+…+MXm+1 =(X1+2X2+3X3+…+MXm )-(X1+X2+X3+…+Xm)+ MXm+1 X3+2X4+3X5+…+MXm+2 =(X2+2X3+3X4+…+MXm+1)-(X2+X3+…+Xm+1)+ MXm+2 如果只是如此,可减少部分计算次数。

  5. 对问题的理解和分析 再观察此两个计算公式,可发现 X2+X3+…+Xm+1 = (X1+X2+X3+…+Xm)-X1+ Xm+1 综上,发现计算过程可转换成2个计算式的递归过程 Result[k]=Result[k-1]-TmpArray[k-1]+Array[i]*m; TmpArray[k]=TmpArray[k-1]-Array[i-m]+Array[i];

  6. 核心代码 int n;int m; cin >> n;cin >> m; //声明3个数组,并进行初始化 int* pArray = new int[n](); memset(pArray,0,sizeof(pArray)); int* pTmpArray = new int[n](); memset(pTmpArray,0,sizeof(pTmpArray)); int* pResultArray= new int[n](); memset(pResultArray,0,sizeof(pResultArray));

  7. //获取士兵能力指数 int max,k,i; for (i=0; i<n; i++) { cin >> pArray[i]; }

  8. for(i=0; i<n; i++) { if(i<m) { pTmpArray[k]+=pArray[i]; pResultArray[k]+=(i+1)*pArray[i]; max =pResultArray[k]; }

  9. else { k++; pTmpArray[k]=pTmpArray[k-1]-pArray[i-m]+pArray[i]; pResultArray[k]=pResultArray[k-1]-pTmpArray[k-1]+pArray[i]*m; if(max<pResultArray[k]) max=pResultArray[k]; } } cout << max;

  10. 算法复杂度分析 • O(n)

  11. 算法的优缺点分析和改进 • 算法优缺点分析: 按照以上程序提交程序,发现有6组测试超时, 经过查找资料发现,cin效率在大数据输入下效率低(由于输入缓存原因),导致程序超时。建议以后输入获取均使用scanf。或者使用std::ios::sync_with_stdio(false);关闭输入输出缓存。详见:https://www.byvoid.com/blog/fast-readfile/

  12. Thanks For Attention

More Related