HDU 3313 Key Vertex

63 篇文章 0 订阅
39 篇文章 0 订阅


Problem Description
You need walking from vertex S to vertex T in a graph. If you remove one vertex which stops you from walking from S to T, that vertex we call as key vertex. Now you are given a directed graph, S and T, and you should tell us how many key vertexes are there in the graph.
Please notice that S and T are key vertexes and if S cannot walking to T by the directed edge in the initial graph then all vertexes becomes to key vertexes.
 

Input
The input consists of multiply test cases. The first line of each test case contains two integers, n(0 <= n <= 100000), m(0 <= m <= 300000), which are the number of vertexes and the number of edge. Each of the next m lines consists of two integers, u, v(0 <= u, v < n; u != v), indicating there exists an edge from vertex u to vertex v. There might be multiple edges but no loops. The last line of each test case contains two integers, S, T(0 <= S, T < n, S != T).

 

Output
Output the number of key vertexes in a single line for each test case.
 

Sample Input
  
  
6 6 0 1 1 2 1 3 2 4 3 4 4 5 0 5
 

Sample Output
  
  
4
找起点和终点的割点,先用bfs算最短路,然后反复在最短路上dfs跳转到最远的点
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define rep(i,j,k) for (int i = j; i <= k; i++)
const int N = 3e5 + 10;
int ft[N], nt[N], u[N], sz;
int n, m, x, y, dis[N], pre[N], flag[N], ans;

bool bfs()
{
    queue<int> p;    p.push(x);
    while (!p.empty())
    {
        int q = p.front(); p.pop();
        if (q == y)
        {
            for (int i = y; i != x; i = pre[i]) flag[i] = dis[i];
            return true;
        }
        for (int i = ft[q]; i != -1; i = nt[i])
        {
            if (dis[u[i]]) continue;
            pre[u[i]] = q;    dis[u[i]] = dis[q] + 1;
            p.push(u[i]);
        }
    }
    return false;
}

int dfs(int x)
{
    if (flag[x]) return x;
    int res = x;
    dis[x] = 1;
    for (int i = ft[x]; i != -1; i = nt[i])
    {
        if (dis[u[i]]) continue;
        int k = dfs(u[i]);
        if (flag[res] < flag[k]) res = k;
    }
    return res;
}

int main()
{
    while (scanf("%d%d", &n, &m) != EOF)
    {
        ans = sz = 0;
        rep(i, 0, n) ft[i] = -1, dis[i] = flag[i] = 0;
        while (m--)
        {
            scanf("%d%d", &x, &y);
            u[sz] = y;    nt[sz] = ft[x]; ft[x] = sz++;
        }
        scanf("%d%d", &x, &y);
        if (!bfs()) { printf("%d\n", n); continue; }
        rep(i, 0, n) dis[i] = 0;
        for (int i = x, k; (k = dfs(i)) != y; flag[i = k] = 0) ans++;
        printf("%d\n", ans + 2);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值