第一种做法是记录下每两个之间的距离,在求最短距离的时候进行逐个累加。最后一个case会超时。
#include<cstdio>
#include<vector>
using namespace std;
int main(){
freopen("1.txt","r",stdin);
int n,d,m,i,sum,e1,e2,distence,tmp;
vector<int> dis;
scanf("%d",&n);
sum=0;
for(i=0;i<n;i++){
scanf("%d",&d);
dis.push_back(d);
sum+=d;
}
scanf("%d",&m);
for(i=0;i<m;i++){
distence=0;
scanf("%d %d",&e1,&e2);
if(e1>e2){
if((e1-e2)<=n/2){
tmp=e1;
e1=e2;
e2=tmp;
}
}
if(e1<e2){
if((e2-e1)>=n/2){
tmp=e1;
e1=e2;
e2=tmp;
}
}
while(e1!=e2){
distence+=dis[e1-1];
e1=(e1+1)%n;
if(e1==0)
e1=n;
}
if(distence>=sum/2)
distence=sum-distence;
printf("%d\n",distence);
}
}
第二种做法是以第一个节点为基准,计算从这个节点到其他所有节点的距离,计算最短距离时,直接相减。
#include<cstdio>
#include<cmath>
#include<vector>
using namespace std;
int main(){
// freopen("1.txt","r",stdin);
int n,m,d,i,e1,e2,distence,sum;
int dis[100001];
scanf("%d",&n);
dis[1]=0;
sum=0;
for(i=1;i<=n;i++){
scanf("%d",&d);
dis[i+1]=dis[i]+d;
sum+=d;
}
scanf("%d",&m);
for(i=0;i<m;i++){
scanf("%d %d",&e1,&e2);
distence=abs(dis[e1]-dis[e2]);
distence = (sum-distence)<distence?sum-distence:distence;
printf("%d\n",distence);
}
}