CF703B Mishka and trip 题解

题目传送门

Step 0 题前闲话

初看这道题,还认为这题是一道贼难的图论题,正解是模拟。

Step 1 解题方法

首先先将所有连线上的权值加起来,时间复杂度 $O(n)$,在处理时用一个 $bool$ 数组 $f$ 来记录是否为省会城市。

代码如下:

Step 2 删除权值

一共有 3 种情况需要扣除权值(设省会城市为 $a_i$,权值为 $q$,总权值为 $ans$ ):

1. 若 $a_i = 1 $ 且未读入 $a_n$ 为省会,$ans = ans - a_x \times a_n$

2. 若 $a_{x \pm 1}$  不为省会城市,$ans = ans - a_x \times a_{x \pm 1}$

3. 若 $a_i = n$$a_1$ 不为省会城市,$ans = ans - a_x \times a_1$

代码如下:

if (x == n && !f[1]) 
            ans -= a[x] * a[1];
        else if (!f[x + 1]) 
            ans -= a[x] * a[x + 1];
        if (x == 1 && !f[n]) 
            ans -= a[x] * a[n];
        else if (!f[x - 1]) 
            ans -= a[x] * a[x - 1];

Step 3 AC code

#include <bits/stdc++.h>
using namespace std;
const int Maxn = 1e5 + 5;
long long n, k, a[Maxn], x, s, ans;
bool f[Maxn];
void check(){
    if (x == n && !f[1]) 
        ans -= a[x] * a[1];
    else if (!f[x + 1]) 
        ans -= a[x] * a[x + 1];
    if (x == 1 && !f[n]) 
        ans -= a[x] * a[n];
    else if (!f[x - 1]) 
        ans -= a[x] * a[x - 1];
}
int main()
{
    scanf("%lld%lld",&n,&k);
    for (int i = 1; i <= n; i ++) {
        scanf("%lld",&a[i]);
        s += a[i], ans += a[i] * a[i - 1];
    }
    ans += a[1] * a[n];
    while (k--) {
        scanf("%lld",&x);
        f[x] = 1,s -= a[x],ans += a[x] * s;
        check();
    }
    printf("%lld",ans);
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值