CodeForces 231E|Cactus|边双联通分量|LCA

本文介绍了一种优化方法,通过利用Tarjan缩点技术和路径间环的数量来快速计算仙人掌图中任意两点间的路径数量,并提供了一个C++实现示例。算法将路径数量表示为2的路径间环个数的幂,从而简化了复杂图的路径计算过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

给定一个仙人掌图,多次询问某两点间的路径数。

发现某两点间的路径数就等于2的路径间环的个数的幂。
因此Tarjan缩点后计算路径经过的环的个数即可。

其实想改成RMQ的,但是太懒了。。

#include <cstdio>
#include <algorithm>
#define FOR(i,j,k) for(i=j;i<=k;++i)
using namespace std;
typedef long long ll;
const int N = 100005, M = 700005, mod = 1000000007, K = 18;
ll qpow(ll a, ll b) {
    ll c = 1;
    for (; b; b >>= 1, a = a * a % mod)
        if (b & 1) c = c * a % mod;
    return c;
}

struct Graph {
    int h[N], p[M], v[M], cnt, pos[N], fa[N][19], num[N];
    int belong[N], sk[N], instack[N], dfn[N], low[N], bcc, n;
    ll dis[N];
    int ts, vis[M], top, dep[N], id[N];
    Graph() { cnt = 1; bcc = 0; ts = 0; top = 0; }
    void add(int a, int b) {
        p[++cnt] = h[a]; v[cnt] = b; h[a] = cnt;
    }

    void tarjan(int x) {
        int i;
        dfn[x] = low[x] = ++ts;
        sk[top++] = x; instack[x] = 1;
        for (i = h[x]; i; i = p[i]) {
            if (vis[i]) continue;
            vis[i] = vis[i ^ 1] = 1;
            if (!dfn[v[i]]) {
                tarjan(v[i]);
                low[x] = min(low[x], low[v[i]]);
            } else if (instack[v[i]])
                low[x] = min(low[x], dfn[v[i]]);
        }
        if (low[x] == dfn[x]) {
            num[++bcc] = 0;
            do {
                i = sk[--top];
                instack[i] = 0;
                belong[i] = bcc;
                num[bcc]++;
            } while (i != x);
            num[bcc] = num[bcc] > 1;
        }
    }

    void build_from(const Graph &g) {
        for (int i = 1; i <= g.n; ++i)
            for (int j = g.h[i]; j; j = g.p[j])
                if (g.belong[i] != g.belong[g.v[j]])
                    add(g.belong[i], g.belong[g.v[j]]);
    }

    void dfs(int x, int f, int *data) {
        int i;
        pos[x] = ++ts; id[ts] = x; fa[x][0] = f; dep[x] = dep[f] + 1;
        dis[x] = dis[f] + data[x];
        FOR(i,1,K) fa[x][i] = fa[fa[x][i - 1]][i - 1];
        for (i = h[x]; i; i = p[i])
            if (v[i] != f) dfs(v[i], x, data);
    }

    int lca(int x, int y) {
        if (dep[x] < dep[y]) swap(x, y);
        int t = dep[x] - dep[y], i;
        FOR(i,0,K) if ((1 << i) & t) x = fa[x][i];
        for(i=K;i>=0;--i) if (fa[x][i] != fa[y][i]) x = fa[x][i], y = fa[y][i];
        return x == y ? x : fa[x][0];
    }
} g, ng;

ll query(int a, int b) {
    a = g.belong[a]; b = g.belong[b];
    int c = ng.lca(a, b);
    return ng.dis[a] + ng.dis[b] - 2 * ng.dis[c] + g.num[c];
}
int main() {
    int n, m, i, q, a, b;
    scanf("%d%d", &n, &m);
    FOR(i,1,m) scanf("%d%d",&a,&b),g.add(a,b),g.add(b,a);
    g.n = n; g.tarjan(1); ng.build_from(g); ng.dfs(1, 0, g.num);
    scanf("%d", &q);
    while (q--) {
        scanf("%d%d", &a, &b);
        printf("%I64d\n", qpow(2, query(a, b)));
    }
    return 0;
}

E. Cactus

A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.

A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, …, vt (t > 2), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1, and also exists an edge between vertices v1 and vt.

A simple path in a undirected graph is a sequence of not necessarily distinct vertices v1, v2, …, vt (t > 0), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1 and furthermore each edge occurs no more than once. We’ll say that a simple path v1, v2, …, vt starts at vertex v1 and ends at vertex vt.

You’ve got a graph consisting of n vertices and m edges, that is a vertex cactus. Also, you’ve got a list of k pairs of interesting vertices xi, yi, for which you want to know the following information — the number of distinct simple paths that start at vertex xi and end at vertex yi. We will consider two simple paths distinct if the sets of edges of the paths are distinct.

For each pair of interesting vertices count the number of distinct simple paths between them. As this number can be rather large, you should calculate it modulo 1000000007 (109 + 7).

Input

The first line contains two space-separated integers n, m (2 ≤ n ≤ 105; 1 ≤ m ≤ 105) — the number of vertices and edges in the graph, correspondingly. Next m lines contain the description of the edges: the i-th line contains two space-separated integers ai, bi (1 ≤ ai, bi ≤ n) — the indexes of the vertices connected by the i-th edge.

The next line contains a single integer k (1 ≤ k ≤ 105) — the number of pairs of interesting vertices. Next k lines contain the list of pairs of interesting vertices: the i-th line contains two space-separated numbers xi, yi (1 ≤ xi, yi ≤ n; xi ≠ yi) — the indexes of interesting vertices in the i-th pair.

It is guaranteed that the given graph is a vertex cactus. It is guaranteed that the graph contains no loops or multiple edges. Consider the graph vertices are numbered from 1 to n.

Output

Print k lines: in the i-th line print a single integer — the number of distinct simple ways, starting at xi and ending at yi, modulo 1000000007 (109 + 7).

Examples

input

10 11
1 2
2 3
3 4
1 4
3 5
5 6
8 6
8 7
7 6
7 9
9 10
6
1 2
3 5
6 9
9 2
9 3
9 10

output

2
2
2
4
4
1
### Codeforces 887E Problem Solution and Discussion The problem **887E - The Great Game** on Codeforces involves a strategic game between two players who take turns to perform operations under specific rules. To tackle this challenge effectively, understanding both dynamic programming (DP) techniques and bitwise manipulation is crucial. #### Dynamic Programming Approach One effective method to approach this problem utilizes DP with memoization. By defining `dp[i][j]` as the optimal result when starting from state `(i,j)` where `i` represents current position and `j` indicates some status flag related to previous moves: ```cpp #include <bits/stdc++.h> using namespace std; const int MAXN = ...; // Define based on constraints int dp[MAXN][2]; // Function to calculate minimum steps using top-down DP int minSteps(int pos, bool prevMoveType) { if (pos >= N) return 0; if (dp[pos][prevMoveType] != -1) return dp[pos][prevMoveType]; int res = INT_MAX; // Try all possible next positions and update 'res' for (...) { /* Logic here */ } dp[pos][prevMoveType] = res; return res; } ``` This code snippet outlines how one might structure a solution involving recursive calls combined with caching results through an array named `dp`. #### Bitwise Operations Insight Another critical aspect lies within efficiently handling large integers via bitwise operators instead of arithmetic ones whenever applicable. This optimization can significantly reduce computation time especially given tight limits often found in competitive coding challenges like those hosted by platforms such as Codeforces[^1]. For detailed discussions about similar problems or more insights into solving strategies specifically tailored towards contest preparation, visiting forums dedicated to algorithmic contests would be beneficial. Websites associated directly with Codeforces offer rich resources including editorials written after each round which provide comprehensive explanations alongside alternative approaches taken by successful contestants during live events. --related questions-- 1. What are common pitfalls encountered while implementing dynamic programming solutions? 2. How does bit manipulation improve performance in algorithms dealing with integer values? 3. Can you recommend any online communities focused on discussing competitive programming tactics? 4. Are there particular patterns that frequently appear across different levels of difficulty within Codeforces contests?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值