题源:https://pintia.cn/problem-sets/994805342720868352/problems/994805435700199424
Ans1:
#include <iostream>
#include <vector>
using namespace std;
// 运行超时,,,需优化。
int main(){
int n,m;
cin>>n;
vector<int> d(n,0);
for(int i=0;i<n;i++){
cin>>d[i];
}
int a,b;
cin>>m;
while(m>=0&&m--){
cin>>a>>b;
if(a>b) swap(a,b);
int s1=0,s2=0;
for(int i=a-1;i<b-1;i++) s1+=d[i];
for(int i=b-1;i<n;i++) s2+=d[i];
for(int i=0;i<a-1;i++) s2+=d[i];
cout<<min(s1,s2)<<endl;
}
return 0;
}
Ans2,优化思路如下:
问题可描述为:整个路径为无向环,一点到一点的顺短还是逆短
1.设计数组D[i]存储1到i+1的距离,那么i与j的顺长度为D[j]-D[i].
2.逆长度设计,总环长度减去顺长度则为逆长度。
3.总环长存储,d[n]
#include <iostream>
#include <vector>
using namespace std;
int main(){
int n,m;
cin>>n;
vector<int> d(n+1,0);//d[0]表示1到1的距离为0
for(int i=1;i<=n;i++){//d[i]为1到i+1的距离,d[n]存储整个环的距离
cin>>d[i];
d[i]+=d[i-1];
}
int a,b;
cin>>m;
while(m--){
cin>>a>>b;
if(a>b) swap(a,b);
int ans=d[b-1]-d[a-1];//1到b的距离减去到a的距离
ans=min(ans,d[n]-ans);//d[n]-ans表示a到b之外的距离
cout<<ans<<endl;
}
return 0;
}
/***
5 1 2 4 14 9
3
1 3
2 5
4 1
*/