HDU 5631 Rikka with Graph

As we know, Rikka is poor at math. Yuta is worrying about this situation, so he gives Rikka some math tasks to practice. There is one of them:

Yuta has a non-direct graph with n vertices and n+1 edges. Rikka can choose some of the edges (at least one) and delete them from the graph.

Yuta wants to know the number of the ways to choose the edges in order to make the remaining graph connected.

It is too difficult for Rikka. Can you help her?



sample input

1

3

1 2

2 3

3 1

1 3



sample output

9



题意

给出一个n个顶点,n+1条边的无向图,最少删除一条边的情况下,图仍然连通,问这样的删除方法数



题解

n顶点至少需要n-1条边才能连通,所有最多删除两条边,暴力枚举,然后BFS判断连通

做题时,有几个问题

1.貌似第一次自己动手BFS判断连通,将第一个顶点入队后忘记book[1]=1,而且只入队没出队,忘记最后q.pop();

2.删除边,貌似已经建图之后很难实现,只好建图的时候直接忽略

3.for(int i=1;i<=G[i].size()-1;++i)这个语句非常危险,因为G[i].size()返回unsigned int,如果是0,0-1的结果会导致RE


#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
#include<algorithm>
#include<iostream>

using namespace std;

int book[105];
queue <int> q;
vector <int> m[105];
pair<int,int> cp[105];

bool bfs(int n);
int main(void)
{
    #ifdef ex
    freopen ("in.txt","r",stdin);
    #endif
    
    int t,n,u,v;
    int i,ii,j,k;
    
    scanf("%d",&t);
    while (t>0)
    {
        scanf("%d",&n);
        for (i=1;i<=n+1;++i)
        {
            scanf("%d%d",&u,&v);
            cp[i].first=u;
            cp[i].second=v;
        }
        
        int ans=0;
        for (i=1;i<=n+1;++i)
        {
            for (ii=i;ii<=n+1;++ii)
            {
                for (j=1;j<=n+1;++j)
                {
                    if (j==i || j==ii) continue;
                    u=cp[j].first;
                    v=cp[j].second;
                    m[u].push_back(v);
                    m[v].push_back(u);
                }  
                if (bfs(n)) ++ans;
                for (k=1;k<=n;++k) m[k].clear();
                memset(book,0,sizeof(book));
            }
        }
        
        printf("%d\n",ans);
        
        --t;
    }
}

bool bfs(int n)
{
    q.push(1);
    int cnt=1;
    book[1]=1;
    while (!q.empty())
    {
        int t=q.front();
        for (int i=0;i<m[t].size();++i)
        {
            int k=m[t][i];
            if (book[k]==0)
            {
                book[k]=1;
                q.push(k);
                ++cnt;
            }
        }
        q.pop();
    }
    
    return cnt==n;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值