HDU 3313 Key Vertex (dfs + bfs)

Source: Internet
Author: User

HDU 3313 Key Vertex (dfs + bfs)
HDU 3313 Key Vertex

Question Link

Question: A directed acyclic graph, finding cut points between s and t

Idea: first, spfa finds a shortest path. If it does not exist, all n are cut points.
Then, each time we perform dfs from s, find the farthest point that can pass through the shortest path, and then this point is the cut point. Next time we start dfs at this point, continue iteration until we find t.

Code:

#include 
 
  #include 
  
   #include 
   
    #include 
    
     #include using namespace std;const int N = 100005;int n, m, s, t, fa[N], vis[N], mark[N], d[N];int first[N], vv[N * 3], next[N * 3], en;const int INF = 0x3f3f3f3f;void addedge(int a, int b) {vv[en] = b;next[en] = first[a];first[a] = en++;}bool bfs() {queue
     
       Q;for (int i = 0; i < n; i++) d[i] = INF;memset(vis, 0, sizeof(vis));Q.push(s);vis[s] = 1;d[s] = 0;while (!Q.empty()) {int u = Q.front();vis[u] = 0;Q.pop();for (int i = first[u]; i + 1; i = next[i]) {int v = vv[i];if (d[v] > d[u] + 1) {d[v] = d[u] + 1;fa[v] = u;if (!vis[v]) {Q.push(v);vis[v] = 1;}}}}if (d[t] >= INF) return false;int tmp = t;memset(mark, 0, sizeof(mark));while (tmp != s) {mark[tmp] = 1;tmp = fa[tmp];}mark[s] = mark[t] = 1;return true;}void dfs(int u) {for (int i = first[u]; i + 1; i = next[i]) {int v = vv[i];if (vis[v]) continue;vis[v] = 1;if (mark[v]) {if (d[v] > d[s])s = v;continue;}dfs(v);}}int main() {while (~scanf("%d%d", &n, &m)) {memset(first, -1, sizeof(first));en = 0;int u, v;while (m--) {scanf("%d%d", &u, &v);addedge(u, v);}scanf("%d%d", &s, &t);if (!bfs()) {printf("%d\n", n);continue;}int ans = 1;memset(vis, 0, sizeof(vis));while (s != t) {dfs(s);ans++;}printf("%d\n", ans);}return 0;}
     
    
   
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.