Poj 1904 King's Quest (strongly connected)

Source: Internet
Author: User
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)

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.