UVA11504- Dominos(Tarjan+缩点)
Posted jzdwajue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA11504- Dominos(Tarjan+缩点)相关的知识,希望对你有一定的参考价值。
题意:多米诺骨牌的游戏。给出一些牌,以及哪张牌倒了之后会推倒哪张牌。求最少的推倒牌的张数,使得全部牌都倒下去。
思路:有向图的强连通分量,用Tarjan缩点之后找出入度为0的点的个数。即为答案。
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int MAXN = 100100; const int MAXM = 100100; struct Edge{ int to, next; }edge[MAXM]; int head[MAXN], tot; int Low[MAXN], DFN[MAXN], Stack[MAXN], Belong[MAXN]; int Index, top; int scc; bool Instack[MAXN]; int num[MAXN]; int dg[MAXN]; int n, m; void init() { tot = 0; memset(head, -1, sizeof(head)); } void addedge(int u, int v) { edge[tot].to = v; edge[tot].next = head[u]; head[u] = tot++; } void Tarjan(int u) { int v; Low[u] = DFN[u] = ++Index; Stack[top++] = u; Instack[u] = true; for (int i = head[u]; i != -1; i = edge[i].next) { v = edge[i].to; if (!DFN[v]) { Tarjan(v); if (Low[u] > Low[v]) Low[u] = Low[v]; } else if (Instack[v] && Low[u] > DFN[v]) Low[u] = DFN[v]; } if (Low[u] == DFN[u]) { scc++; do { v = Stack[--top]; Instack[v] = false; Belong[v] = scc; num[scc]++; } while (v != u); } } void solve() { memset(Low, 0, sizeof(Low)); memset(DFN, 0, sizeof(DFN)); memset(num, 0, sizeof(num)); memset(Stack, 0, sizeof(Stack)); memset(Instack, false, sizeof(Instack)); Index = scc = top = 0; for (int i = 1; i <= n; i++) if (!DFN[i]) Tarjan(i); } int main() { int cas; scanf("%d", &cas); while (cas--) { init(); scanf("%d%d", &n, &m); int u, v; for (int i = 0; i < m; i++) { scanf("%d%d", &u, &v); addedge(u, v); } solve(); memset(dg, 0, sizeof(dg)); for (int u = 1; u <= n; u++) { for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; if (Low[u] != Low[v]) dg[Belong[v]]++; } } int ans = 0; for (int i = 1; i <= scc; i++) if (dg[i] == 0) ans++; printf("%d\n", ans); } return 0; }
以上是关于UVA11504- Dominos(Tarjan+缩点)的主要内容,如果未能解决你的问题,请参考以下文章
UVA796 - Critical Links(Tarjan求桥)
UVA - 796 Critical Links (tarjan,无向图桥)