1046. Shortest Distance (20)
来源:互联网 发布:工业设计手绘工具知乎 编辑:程序博客网 时间:2024/05/16 11:17
1.建立一个数组dp[i],记录0到i之间的距离和
2.定义sum,记录全程的路程和
3.求i,j的最短距离时,利用ans=dp[j]-[i]+num[i]-num[j],ans2=sum-ans,min(ans,ans2)即为答案
AC代码:
#include <iostream>#include <stdio.h>#include <vector>#include <stack>#include <algorithm>#include <memory.h>#include <map>#include <set>#include "limits.h"using namespace std;int main(void){ int n; scanf("%d",&n); int *num=new int[n]; int *dp=new int[n]; memset(dp, 0, sizeof(dp)); int sum=0; for(int i=0;i<n;i++) { scanf("%d",&num[i]); if(i==0) dp[i]=num[i]; else dp[i]=dp[i-1]+num[i]; sum+=num[i]; } int m; scanf("%d",&m); for(int i=0;i<m;i++) { int a,b; scanf("%d %d",&a,&b); if(a>b) swap(a,b); int tmp=dp[b-1]-dp[a-1]+num[a-1]-num[b-1]; int tmp2=sum-tmp; printf("%d\n",min(tmp2,tmp)); } return 0;}
0 0
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- 1046. Shortest Distance (20)
- Populating Next Right Pointers in Each Node
- 简单理解Apache,Mysql,PHP之间的联系
- URAL 1354 Palindrome. Again Palindrome (回文 + KMP)
- WebKit之网络栈
- NSInvocation类的学习
- 1046. Shortest Distance (20)
- WebKit之多进程模型
- MySQL 创建、修改和删除表
- 最简单的贪心
- WebKit之消息循环
- RichEdit
- 记一次PHP开发过程中,json_decode返回null的解决情况
- WebKit之多线程模型
- WebKit之多进程模型2