SGU 210. Beloved Sons(二分图匹配)

来源:互联网 发布:平湖市行知小学教师表 编辑:程序博客网 时间:2024/05/02 02:17

题目链接:点击打开链接

思路:

本题可以用网络流来解, 从源点向每个王子连一条容量为国王喜爱程度的边, 每个王子向每个他喜欢的女孩也连一条容量为喜爱程度的边, 每个女孩向汇点连一条容量INF的边。

一个更简单的方法是: 考虑匈牙利算法从1~n, 一定会尽量满足前面的人, 所以我们只需要按照国王对王子的喜爱程度排序之后做匈牙利算法即可。

细节参见代码:

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>#include<string>#include<vector>#include<stack>#include<bitset>#include<cstdlib>#include<cmath>#include<set>#include<list>#include<deque>#include<map>#include<queue>#define Max(a,b) ((a)>(b)?(a):(b))#define Min(a,b) ((a)<(b)?(a):(b))using namespace std;typedef long long ll;typedef long double ld;const ld eps = 1e-9, PI = 3.1415926535897932384626433832795;const int mod = 1000000000 + 7;const int INF = 0x3f3f3f3f;const int seed = 131;const ll INF64 = ll(1e18);const int maxn = 500*2 + 10;int from[maxn], use[maxn], n, k, v, tot, ans[maxn];vector<int> g[maxn];struct node {    int id, v;    node(int id=0, int v=0):id(id), v(v) {}    bool operator < (const node& rhs) const {        return v > rhs.v;    }}like[maxn];bool match(int x) {    int len = g[x].size();    for(int i = 0; i < len; i++)    if(!use[g[x][i]]) {        use[g[x][i]] = true;        if(from[g[x][i]] == -1 || match(from[g[x][i]])) {            from[g[x][i]] = x;            return true;        }    }    return false;}int hungary(int n) {    tot = 0;    memset(from, -1, sizeof(from));    for(int i = 1; i <= n; i++) {        memset(use, 0, sizeof(use));        if(match(like[i].id)) ++tot;    }    return tot;}int main() {    while(~scanf("%d",&n)) {        for(int i = 1; i <= n; i++) {            scanf("%d", &like[i].v);            like[i].id = i;        }        sort(like+1, like+n+1);        for(int i = 1; i <= n; i++) {            scanf("%d", &k);            for(int j = 1; j <= k; j++) {                scanf("%d", &v);                g[i].push_back(v);            }        }        hungary(n);        for(int i = 1; i <= n; i++) {            if(from[i] == -1) continue;            ans[from[i]] = i;        }        for(int i = 1; i <= n; i++) {            printf("%d%c", ans[i], i == n ? '\n' : ' ');        }    }    return 0;}


0 0