题意: 一个国家有n个城市,k个首都,城市是一个从1~n~1的一个环,首都通向各个城市。每两个城市间每条路的花费等于两个城市的val的城市,问你遍历所有的路的总花费。
#include <bits/stdc++.h>
#define MAXN 100005
using namespace std;
int main() {
int n,m,k,cap[MAXN],c[MAXN] ;
bool vis[MAXN];
while (scanf("%d%d", &n, &k) != EOF) {
__int64 sum = 0; memset(vis, false, sizeof(vis));
//用sum记录所有城市的总的魅力值
for (int i = 0; i < n; i++) {
scanf("%d", &c[i]);
sum += c[i];
}
__int64 ans = c[0]*c[n-1];
//在没有首都的情况下
for (int i = 0; i < n - 1; i++) {
ans += c[i]*c[i + 1];
}
for (int i = 0; i < k; i++) {
scanf("%d", &m);
if (m == 1) {
//防止两个首都情况
if (vis[n]) ans += c[m-1]*c[n-1];
if (vis[m + 1]) ans += c[m]*c[m-1];
ans += c[m-1]*(sum -c[m-1]-c[m]-c[n-1]);
}
else if (m == n) {
//cout << ans << endl;
if (vis[m-1]) ans += c[m-1]*c[m-2];
if(vis[1]) ans += c[m-1]*c[0];
//cout << ans << endl;
ans += c[m-1]*(sum - c[m-1]-c[0]-c[m-2]);
}
else {
if (vis[m-1]) ans += c[m-1]*c[m-2];
if(vis[m+1]) ans += c[m-1]*c[m];
ans += c[m-1]*(sum - c[m-1]-c[m-2]-c[m]);
}
vis[m] = true; sum -= c[m-1];
//cout<<m<<" "<<sum<<" "<<ans<<endl;
}
printf("%lld\n", ans);
}
return 0;
}