sgu 210 分类: sgu 2015-06-18 23:05 30人阅读 评论(0) 收藏


KM,把王子放在二分图X侧,妹子放在Y侧,边权为(Ai)2KM即可,
具体实现时我把王子放在二分图Y侧,妹子放在X侧,这样就更容易输出答案了。


#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<cmath>
#include<cstring>
#include<map>
#include<string>
#include<stack>
#include<queue>
#include<utility>
#include<iostream>
#include<algorithm>

const int maxn = 405, INF = 0x3f3f3f3f;

int n, a[maxn];
int w[maxn][maxn];
bool visx[maxn], visy[maxn];
int slack[maxn], lx[maxn], ly[maxn];
int linky[maxn];

void init()
{
    std::cin >> n;
    for(int i = 1; i <= n; i++)
        std::cin >> a[i];
    for(int i = 1, num; i <= n; i++)
    {
        std::cin >> num;
        for(int j = 1, to; j <= num; j++)
            std::cin >> to, w[to][i] = a[i]*a[i];
    }
}
bool find(int x)
{
    visx[x] = true;

    for(int y = 1; y <= n; y++)
        if(!visy[y])
        {
            int dec = lx[x] + ly[y] - w[x][y];

            if(!dec)
            {
                visy[y] = true;
                if(!linky[y] || find(linky[y]))
                {
                    linky[y] = x;
                    return true;
                }
            }
            slack[y] = std::min(slack[y], dec);
        }
    return false;   
}
void KM()
{
    memset(lx,0,sizeof(lx));
    memset(ly,0,sizeof(ly));
    memset(linky,0,sizeof(linky));

    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            lx[i] = std::max(lx[i],w[i][j]);

    for(int i = 1; i <= n; i++)
    {
        memset(slack,INF,sizeof(slack));

        while(true)
        {
            memset(visx,false,sizeof(visx));
            memset(visy,false,sizeof(visy));

            if(find(i)) break;

            int d = INF;

            for(int i = 1; i <= n; i++)
                if(!visy[i]) d = std::min(slack[i], d);
            for(int i = 1; i <= n; i++)
            {
                if(visx[i]) lx[i] -= d; 
                if(visy[i]) ly[i] += d;
                else slack[i] -= d;
            }
        }
    }
}
void prt()
{
    for(int i = 1; i <= n; i++)
        std::cout << (w[linky[i]][i]?linky[i]:0) << ' ';
}


int main()
{
#ifndef ONLINE_JUDGE
    freopen("sgu210.in","r",stdin);
    freopen("sgu210.out","w",stdout);
#endif

    init(), KM(), prt();

#ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-06-18 23:05  <Dash>  阅读(132)  评论(0编辑  收藏  举报