Poj 1904 King's quest
Question Link
Question: N men, each of whom has a list of women they like. Now let's give them a perfect match and ask all the women in the perfect match list that each person may marry.
Idea: strong connectivity, creating a picture, a man points a side to a female, then a perfectly matched edge to a man, and then asks for strong connectivity, in the same strongly connected branch and what you want to marry
Code:
#include <cstdio>#include <cstring>#include <vector>#include <algorithm>#include <stack>using namespace std;const int N = 4005;int n;vector<int> g[N];int ans[N], an;stack<int> S;int pre[N], dfn[N], dfs_clock, sccno[N], sccn;void dfs_scc(int u) {pre[u] = dfn[u] = ++dfs_clock;S.push(u);for (int i = 0; i < g[u].size(); i++) {int v = g[u][i];if (!pre[v]) {dfs_scc(v);dfn[u] = min(dfn[u], dfn[v]);} else if (!sccno[v]) dfn[u] = min(dfn[u], pre[v]);}if (pre[u] == dfn[u]) {sccn++;while (1) {int x = S.top(); S.pop();sccno[x] = sccn;if (x == u) break;}}}void find_scc() {dfs_clock = sccn = 0;memset(pre, 0, sizeof(pre));memset(sccno, 0, sizeof(sccno));for (int i = 1; i <= 2 * n; i++)if (!pre[i]) dfs_scc(i);}int main() {while (~scanf("%d", &n)) {for (int i = 1; i <= 2 * n; i++) g[i].clear();int a, b;for (int i = 1; i <= n; i++) {scanf("%d", &a);while (a--) {scanf("%d", &b);g[i].push_back(b + n);}}for (int i = 1; i <= n; i++) {scanf("%d", &a);g[a + n].push_back(i);}find_scc();for (int i = 1; i <= n; i++) {an = 0;for (int j = 0; j < g[i].size(); j++) {if (sccno[i] == sccno[g[i][j]])ans[an++] = g[i][j] - n;}sort(ans, ans + an);printf("%d", an);for (int j = 0; j < an; j++)printf(" %d", ans[j]);printf("\n");}}return 0;}
Poj 1904 King's Quest (strongly connected)