Educational Codeforces Round 40 (Rated for Div. 2) D. Fight Against Traffic

49 篇文章 0 订阅
14 篇文章 0 订阅

题目大意

给出一个 n n n个点, m m m条边的无向图,无重边,且边权都为1。
并指定起点 s s s,和终点 t t t
问有多少种增加一条边(不能产生重边)的方案,使得从 s s s t t t的最短路不会发生改变。

时间限制

1s

数据范围

n , m ≤ 1000 n,m\le 1000 n,m1000

题解

因为边权都为1,所以直接BFS即可求出最短路。
由于 n n n非常小,于是可以直接枚举增加哪一条边。
但是如果每一次都BFS一边,那么总的时间复杂度就是 O ( n 3 ) O(n^3) O(n3)并不是能接受的。
这时候,就要想办法把已知最短路的信息利用起来。
有没有快速求出经过新增加这条边最短路的方法呢?
答案是有的,
f i f_i fi表示从 s s s出发到 i i i的最短路, g i g_i gi表示从 t t t出发到 i i i的最短路,
那么经过新增加的这条边 ( x , y ) \pod{x,y} (x,y)的从 s s s t t t的最短路就是 f x + 1 + g y f_x+1+g_y fx+1+gy

Code

//#pragma GCC optimize (2)
//#pragma G++ optimize (2)
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#define G getchar
#define ll long long
using namespace std;

int read()
{
    char ch;
    for(ch = G();(ch < '0' || ch > '9') && ch != '-';ch = G());
    int n = 0 , w;
    if (ch == '-')
    {
        w = -1;
        ch = G();
    } else w = 1;
    for(;'0' <= ch && ch <= '9';ch = G())n = (n<<1)+(n<<3)+ch-48;
    return n * w;
}

const int N = 1003;

int n , f[N] , g[N] , ans , m , x , y;
int s , t;
int lst[N] , to[N * 2] , tot , nxt[N * 2];
int q[10 * N] , l , r , S;
bool flag[N][N];
int tx , ty;
bool bz[N];

void bfs(int x)
{
    int y;
    l = 0;
    r = 1;
    memset(f , 127 , sizeof(f));
    f[x] = 0;
    q[1] = x;
    for (; l < r; )
    {
        l++;
        y = q[l];
        for (int i = lst[y] ; i ; i = nxt[i])
            if (f[to[i]] > f[y] + 1)
            {
                f[to[i]] = f[y] + 1;
                r++;
                q[r] = to[i];
            }

    }
}

void ins(int x , int y)
{
    tot++;
    nxt[tot] = lst[x];
    to[tot] = y;
    lst[x] = tot;
}

int main()
{
    //freopen("h.in","r",stdin);
    //freopen("h.out","w",stdout);

    n = read();
    m = read();
    s = read();
    t = read();

    memset(flag , 0 , sizeof(flag));

    for (int i = 1 ; i <= m ; i++)
    {
        x = read();
        y = read();
        flag[x][y] = flag[y][x] = 1;
        ins(x , y);
        ins(y , x);
    }

    bfs(s);
    memcpy(g , f , sizeof(g));
    bfs(t);

    for (int i = 1 ; i <= n; i++)
        for (int j = i + 1 ; j <= n ; j++)
            if (flag[i][j] == 0)
            {
                if (g[t] <= min(f[i] + g[j] + 1 , f[j] + g[i] + 1)) ans++;
            }

    printf("%d\n", ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值