题目大意:给一张有向图,求一个结点数最大的结点集,使得该结点集中的任意两个结点u和v满足:要么u可以达v,要么v可以达u,(u,v相互可达也行)。
思路:不难发现,如果要使得结点数最大,那么同一个强连通分量中的点,要么全选,要么全不选,让每一个SCC结点的权等于它的结点数,则题目可以转换为求SCC图上权的最长路径,SCC图是DAG图,可以同动态规划求解。
一开始,Tarjan写错了,WA了2次。
#include <iostream> #include <cstdlib> #include <cstring> #include <cstdio> #include <string> #include <algorithm> using namespace std; const int maxn = 1010; const int maxm = 50010; struct Edge { int v, next; }edge[maxm]; int G[maxn][maxn]; int first[maxn], stack[maxn], ins[maxn], dfn[maxn], low[maxn]; int belong[maxn]; int d[maxn], w[maxn], vis[maxn]; int n, m; int cnt; int scnt, top, tot; void init() { cnt = 0; scnt = top = tot = 0; memset(G, 0, sizeof(G)); memset(first, -1, sizeof(first)); memset(dfn, 0, sizeof(dfn)); memset(ins, 0, sizeof(ins)); memset(d, 0, sizeof(d)); memset(w, 0, sizeof(w)); memset(vis, 0, sizeof(vis)); } void read_graph(int u, int v) { edge[cnt].v = v, edge[cnt].next = first[u]; first[u] = cnt++; } void dfs(int u) { int v; low[u] = dfn[u] = ++tot; stack[top++] = u; ins[u] = 1; for(int e = first[u]; e != -1; e = edge[e].next) { v = edge[e].v; if(!dfn[v]) { dfs(v); low[u] = min(low[u], low[v]); } else if(ins[v]) { low[u] = min(low[u], dfn[v]); } } if(low[u] == dfn[u]) { scnt++; do { v = stack[--top]; belong[v] = scnt; ins[v] = 0; }while(u != v); } } void Tarjan() { for(int v = 1; v <= n; v++) if(!dfn[v]) dfs(v); } void read_case() { init(); scanf("%d%d", &n, &m); while(m--) { int u, v; scanf("%d%d", &u, &v); read_graph(u, v); } } int dp(int i) { int &ans = d[i]; if(vis[i]) return ans; vis[i] = 1; ans = w[i]; for(int j = 1; j <= scnt; j++) if(G[i][j]) { ans = max(ans, dp(j)+w[i]); } return ans; } void solve() { read_case(); Tarjan(); for(int i = 1; i <= n; i++) w[belong[i]]++; //权值 for(int u = 1; u <= n; u++) { for(int e = first[u]; e != -1; e = edge[e].next) { int v = edge[e].v; if(belong[u] != belong[v]) { G[belong[u]][belong[v]] = w[belong[u]]; //重构图 } } } int ans = 0; for(int i = 1; i <= scnt; i++) { ans = max(ans, dp(i)); } printf("%d\n", ans); } int main() { int T; scanf("%d", &T); while(T--) { solve(); } return 0; }