hdu 3371 Connect the Cities(最小生成树)

来源:互联网 发布:java poi 导出excel 编辑:程序博客网 时间:2024/06/06 12:49

/* hdu 神坑啊!  c++能过g++TLE!!!尼玛

*/

#include<cstdio>

#include<cstring>
#define INF 1<<30
int map[510][510],low[510],vis[510];
int n,m,k;
int init()
{
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= n; j++)
            map[i][j] = INF;
    memset(vis,0,sizeof(vis));
    return 0;
}


int prim()
{
    int ans=0;
    for(int i = 0; i <= n; i++)
        low[i] = map[1][i];
    vis[1] = 1;
    for(int i = 1; i < n; i++)
    {
        int temp = INF,pos=-1;
        for(int j = 1; j <= n; j++)
            if(!vis[j]&&temp>low[j])
            {
                temp=low[j];
                pos = j;
            }
        if(pos==-1) return -1;
        vis[pos] = 1;
        ans += low[pos];
        for(int j = 1; j <= n; j++)
            if(!vis[j]&&low[j]>map[pos][j])
                low[j] = map[pos][j];
    }
    return ans;
}
int main()
{
    int t,a,b,c;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d %d",&n,&m,&k);
        init();
        for(int i = 0; i < m; i++)
        {
            scanf("%d%d%d",&a,&b,&c);
            if(c<map[a][b])
            map[a][b] = map[b][a] = c;
        }
        int tm[510];
        while(k--)
        {
            scanf("%d",&a);
            for(int i = 0; i < a; i++)
            {
                scanf("%d",&tm[i]);
            }
            for(int i = 0; i < a; i++)
                for(int j = 0; j < a; j++)
                    if(i!=j)
                        map[tm[i]][tm[j]] = 0;
        }
        printf("%d\n",prim());
    }
    return 0;
}
原创粉丝点击