1241: Graph Connectivity

该博客介绍了一个关于图连通性的编程问题,目标是找出给定图中的最大连通子图数量。输入是一个包含节点连接信息的字符序列,输出是连通子图的个数。程序使用深度优先搜索(DFS)进行遍历,并通过一个示例输入和输出展示了其工作原理。

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

 1241: Graph Connectivity


ResultTIME LimitMEMORY LimitRun TimesAC TimesJUDGE
3s8192K551201Standard

Consider a graph G formed from a large number of nodes connected by edges. G is said to be connected if a path can be found in 0 or more steps between any pair of nodes in G. For example, the graph below is not connected because there is no path from A to C.

 

 

This graph contains, however, a number of subgraphs that are connected, one for each of the following sets of nodes: {A}, {B}, {C}, {D}, {E}, {A,B}, {B,D}, {C,E}, {A,B,D}

A connected subgraph is maximal if there are no nodes and edges in the original graph that could be added to the subgraph and still leave it connected. There are two maximal connected subgraphs above, one associated with the nodes {A, B, D} and the other with the nodes {C, E}.

Write a program to determine the number of maximal connected subgraphs of a given graph.

Input and Output

The first line of input contains a single uppercase alphabetic character. This character represents the largest node name in the graph. Each successive line contains a pair of uppercase alphabetic characters denoting an edge in the graph. The sample input section contains a possible input set for the graph pictured above.

Input is terminated by a blank line.

 

Write in the output the number of maximal connected subgraphs.

Sample Input

 

E
AB
CE
DB
EC

Sample Output

 

2

 

 


This problem is used for contest: 119  151 

 

#include<stdio.h>
#include<string.h>
int a[50][50];
int vis[50];
int sum;
void dfs(int step)
{
    int i;
    vis[step]=1;
    for(i=1;i<=sum;i++)
    {
        if(vis[i]==0&&a[step][i]==1)
        {
            dfs(i);
        }
    }
}
int main()
{
    char ch;
    int i,j;
    while(scanf("%c",&ch)==1)
    {
        getchar();
        memset(vis,0,sizeof(vis));
        memset(a,0,sizeof(a));
         sum=ch-'A'+1;
        char ch1,ch2;
        while(scanf("%c",&ch1)==1)
        {
            if(ch1=='/n') break;
            scanf("%c",&ch2);
            getchar();
            i=ch1-'A'+1;
            j=ch2-'A'+1;
            a[i][j]=a[j][i]=1;
        }
        int count=0;
        for(i=1;i<=sum;i++)
        {
            if(vis[i]==0)
            {
                count++;
                 dfs(i);
            }
        }
        printf("%d/n",count);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值