poj3026一道最小生成树(wa到死)

本文介绍了一种基于最小生成树算法解决特定问题的方法,并通过具体实现案例进行了详细讲解。涉及核心算法、图遍历及输入处理等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


其实就是一道傻逼最小生成树,只因为输入时,为了吃的scanf剩下的换行符,用了getchar()结果wa到死





#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>

using namespace std;

struct edge{
    int from,to,cost;
    bool operator<(const edge & a)const
    {
        return cost < a.cost;
    }
}es[1000010];
char str[55][55];
int s[110][2];
int fa[110],e,dist[55][55],vis[55][55];
void init()
{
    for(int i=0;i<110;i++)fa[i]=i;
}
int find_p(int x)
{
    if(x!=fa[x])fa[x]=find_p(fa[x]);
    return fa[x];
}
void unite(int x,int y)
{
    x=find_p(x);
    y=find_p(y);
    if(x!=y)fa[x]=y;
}
int kruskal()
{
    init();
    sort(es,es+e);
    //for(int i=0;i<e;i++)printf("%d %d %d\n",es[i].from,es[i].to,es[i].cost);
    int res=0;
    for(int i=0;i<e;i++){
        if(find_p(es[i].from)!=find_p(es[i].to)){
            unite(es[i].from,es[i].to);
            res+=es[i].cost;
        }
    }
    return res;
}
int bfs(int sx,int sy)
{
    int dx[4]={-1,0,1,0},dy[4]={0,1,0,-1};
    queue<pair<int,int> > que;
    memset(vis,0,sizeof(vis));
    memset(dist,0,sizeof(dist));
    que.push(make_pair(sx,sy));
    vis[sx][sy]=1;
    while(!que.empty()){
        pair<int,int> p=que.front();que.pop();
        for(int i=0;i<4;i++){
            int tx=p.first+dx[i],ty=p.second+dy[i];
            if(!vis[tx][ty]&&str[tx][ty]!='#'){
                vis[tx][ty]=1;
                dist[tx][ty]=dist[p.first][p.second]+1;
                que.push(make_pair(tx,ty));
            }
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--){
        int n,m,tot=0;e=0;
        scanf("%d%d",&n,&m);getchar();//会wa,只有gets()能a;
        for(int i=0;i<m;i++){
            gets(str[i]);
            for(int j=0;j<n;j++){
                if(str[i][j]=='S'||str[i][j]=='A')s[tot][0]=i,s[tot][1]=j,tot++;
            }
        }
        //cout<<tot<<endl;
        for(int i=0;i<tot;i++){
            bfs(s[i][0],s[i][1]);
            for(int j=i+1;j<tot;j++){
                es[e].from=i,es[e].to=j,es[e].cost=dist[s[j][0]][s[j][1]];e++;
                es[e].from=j,es[e].to=i,es[e].cost=dist[s[j][0]][s[j][1]];e++;
            }
        }
        printf("%d\n",kruskal());
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值