Codeforces Round #606 (Div. 2, based on Technocup 2020 Elimination Round 4) dfs + 思维

传送门

文章目录

题意:

给一张图,求必须经过 a a a点和 b b b点的路径条数。

思路:

通过观察我们发现,这个路径无非就是 x − > a − > b − > y x->a->b->y x>a>b>y或者 x − > b − > a − > y x->b->a->y x>b>a>y,我们只需要找到 x x x y y y点的个数让后他们乘起来即为路径条数。
我们分别求 x , y x,y x,y。我们需要转换一下题目的问法,可以拆成两个问题:
(1)从 a a a开始不经过 b b b不能到达的点。
(2)从 b b b开始不经过 a a a不能到达的点。
这里只讨论第一种情况,第二种同理。我们一遍从 a a a开始dfs的时候,只需要将 b b b这个点设置为已经经过的点,形象一下就是把这个点堵上,让后能到的点就是不必须经过 b b b就能到的点,用总点数 n n n减去即可。

//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;

//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;

const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;

int n,m,cnt;
vector<int>v[N];
bool st[N];

void init()
{
    
    
    for(int i=1;i<=n;i++) st[i]=0;
}

void dfs(int u)
{
    
    
    cnt++; st[u]=1;
    for(auto x:v[u]) if(!st[x]) dfs(x);
}

int main()
{
    
    
//	ios::sync_with_stdio(false);
//	cin.tie(0);

    int _; scanf("%d",&_);
    while(_--)
    {
    
    
        int a,b;
        scanf("%d%d%d%d",&n,&m,&a,&b);
        for(int i=1;i<=m;i++)
        {
    
    
            int a,b; scanf("%d%d",&a,&b);
            v[a].pb(b); v[b].pb(a);
        }
        LL x,y;
        cnt=0; st[b]=1; dfs(a); x=n-cnt-1; init();
        cnt=0; st[a]=1; dfs(b); y=n-cnt-1; init();
        printf("%lld\n",x*y);
        for(int i=1;i<=n;i++) v[i].clear();
    }


	return 0;
}
/*

*/



猜你喜欢

转载自blog.csdn.net/m0_51068403/article/details/115072588