prime算法_最小生成树

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include
using namespace std;
#define LL long long
const int N = 2000;
const int INF = 0x3f3f3f;
struct Node
{
    int to,next,w;
    bool operator < (const Node &a) const
    {
        return w > a.w;
    }
} Edge[20000],t1,t2;
int dis[N],vis[N],head[N],cnt;
int res;
void addedge(int u,int v,int w)
{
    Edge[cnt].to= v;
    Edge[cnt].next = head[u];
    Edge[cnt].w = w;
    head[u] = cnt++;
}
void init()
{
        //memset(Edge,0,sizeof(Edge));
        memset(head,-1,sizeof(head));
        memset(vis,0,sizeof(vis));
        memset(dis,INF,sizeof(dis));
        res=0;
        cnt=0;
}
void prim(int s)
{
    priority_queue q;
    for(int i = head[s] ; i != -1 ; i = Edge[i].next)
    {
        int v = Edge[i].to;
        if(Edge[i].w < dis[v])
        {
            dis[v] = Edge[i].w;
            t1.w = dis[v];
            t1.to =  v;
            q.push(t1);
        }
    }
    vis[s] = 1;
    // printf("u:%d dis:%d\n",s,dis[s]);
    while(!q.empty())
    {
        t1 = q.top();
        q.pop();
        int u = t1.to;
        if(vis[u]) continue;
        vis[u] = 1;
       // printf("u:%d dis:%d\n",u,dis[u]);
        res += dis[u];
        for(int i = head[u]; i != -1; i = Edge[i].next)
        {
            int v = Edge[i].to;
            if(!vis[v] && dis[v] > Edge[i].w)
            {
                dis[v] = Edge[i].w;
                t2.to = v;
                t2.w = dis[v];
                q.push(t2);
            }
        }
    }
}
int main()
{
    int t, n,m,r,w,a,b;
    scanf("%d",&t);
    while(t--)
    {

        res=0;
         scanf("%d%d%d",&n,&m,&r);
        init();
        for(int i=0; i

你可能感兴趣的:(prime算法_最小生成树)