标签:problem ace out code space break div else 效率
[Time Gate]
https://www.luogu.org/problemnew/show/P2746
【解题思路】
Tarjan缩点
第一问就过于水了,缩完点后,输出入度为0的点的个数即可。
第二问略微麻烦,考虑出度为零的点是一定不合法的,想让它合法,最有效率的一种方法就是让他连到一个入度为零的点上,而且如果有选择的余地的话,尽量让他连到一个走不到它的入度为0的点上,如果都能走到它那随便连也没问题。 当然入度为零的点多于出度为零的点的话也是不合法的,那就找一个出度为零(可以重复)的点连过去就好了。
设入度为零的点有cnt1个,出度为零的有cnt2个。
则答案为:max(cnt1,cnt2)
【code】
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdio> 5 #include <cctype> 6 #include <cmath> 7 8 using namespace std; 9 10 const int N = 1020; 11 12 int n, ec = -1, a, b, id = 0, top, cur, ans = 0, color = 0, cnt; 13 int siz[N], dfn[N], f[N], low[N], stk[N], in[N], vis[N], col[N], out[N]; 14 15 struct Edge 16 { 17 int u, v, nxt; 18 }e[N << 2]; 19 20 inline void Addedge(int a, int b) 21 { 22 ++ec; 23 e[ec].u = a; 24 e[ec].v = b; 25 e[ec].nxt = f[a]; 26 f[a] = ec; 27 } 28 29 inline void read(int &x) 30 { 31 int k = 1; x = 0; 32 char c = getchar(); 33 while (!isdigit(c)) 34 if (c == ‘-‘) c = getchar(), k = -1; 35 else c = getchar(); 36 while (isdigit(c)) 37 x = (x << 1) + (x << 3) + (c ^ 48), 38 c = getchar(); 39 x *= k; 40 } 41 42 void Tarjan(int u) 43 { 44 dfn[u] = low[u] = ++id; 45 stk[++top] = u, vis[u] = 1; 46 for (int i = f[u]; i != -1; i = e[i].nxt) 47 if (!dfn[e[i].v]) 48 Tarjan(e[i].v), low[u] = min(low[u], low[e[i].v]); 49 else if (vis[e[i].v]) 50 low[u] = min(low[u], dfn[e[i].v]); 51 if (dfn[u] == low[u]) 52 { 53 ++color; 54 do 55 { 56 cur = stk[top--]; 57 vis[cur] = 0; 58 ++siz[color]; 59 col[cur] = color; 60 }while (cur != u); 61 } 62 } 63 64 signed main() 65 { 66 read(n); 67 memset(f, -1, sizeof(f)); 68 for (int i = 1; i <= n; ++i) 69 while (true) 70 { 71 read(b); 72 if (!b) break; 73 Addedge(i, b); 74 } 75 for (int i = 1; i <= n; ++i) 76 if (!dfn[i]) 77 Tarjan(i); 78 for (int i = 0; i <= ec; ++i) 79 if (col[e[i].u] != col[e[i].v]) 80 ++in[col[e[i].v]], ++out[col[e[i].u]]; 81 for (int i = 1; i <= color; ++i) 82 { 83 if (!in[i]) ++ans; 84 if (!out[i]) ++cnt; 85 } 86 printf("%d\n%d", ans, color == 1 ? 0 : max(cnt, ans)); 87 return 0; 88 }
[USACO5.3]校园网Network of Schools
标签:problem ace out code space break div else 效率
原文地址:https://www.cnblogs.com/66dzb/p/11161393.html