uva459(并查集)

https://vjudge.net/problem/UVA-459(poj459 点击打开链接)

思路:并查集,检查连通分量(树)的个数
分析:普通的并查集板子,最后父节点是自己的是一颗树,计数输出就可以了。思路是对的,就卡在输入上了。。。。

代码:


#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <string.h>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <cstdio>
#include <iterator>

using namespace std;

const int maxn = 30;
int t = 0,temp,father[maxn];

void init()
{
    for(int i = 0;i <= maxn;i++)
        father[i] = i;
}

void unin(int a,int b)
{
    father[a] = b;//自己指定“靠右”原则
}

int find(int x)
{
    if(x == father[x])
        return x;
    int y = find(father[x]);
    return father[x] = y;
}

void solve()
{
   string ch;
   getline(cin,ch);
   temp = ch[0] - 'A' + 1;
   while(getline(cin,ch))
   {
       //getline可以读空格或空行
       //输入空行时,该组样例结束
       if(!ch[0])break;
       int p = find(ch[0] - 'A' + 1),q = find(ch[1] - 'A' + 1);
       if(p != q)
        unin(p,q);

   }
}

void output()
{
    int cnt = 0;
    for(int i = 1;i <= temp;i++)
    {
        if(i == father[i])
            cnt++;
    }
    printf("%d\n",cnt);
    if(t)
        printf("\n");
}

int main()
{
    while(cin >> t)//最大的测试样例也是循环的
    {
        getchar();//吃掉回车
        getchar();//读入一个空行
        while(t--)
        {
            init();
            solve();
            output();
        }
    }
}

鉴于死在了输入上,回顾一波输入输出函数

  1. scanf函数,不能读空格。
  2. getchar函数,可以读空格,用来吃掉回车(getchar()就可以),也可以读单个字符(char ch; ch = getchar())。
  3. gets函数,读入字符串,也可以读空格。输入字符串时,如果上一个输入结束后有回车,并且没有用getchar吃掉的话,gets函数就会读入回车,而不会 读入字符串。
  4. getline函数,可以读入空格、回车。用法:string ch; getline(cin,ch);需要注意的是,输入的必须是string类型的,不能是char。
  5. cin函数不能读入空格。
  6. puts函数可以自动输出换行,输出字符串后自动换行,不用加’\n’。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值