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();
}
}
}
鉴于死在了输入上,回顾一波输入输出函数
- scanf函数,不能读空格。
- getchar函数,可以读空格,用来吃掉回车(getchar()就可以),也可以读单个字符(char ch; ch = getchar())。
- gets函数,读入字符串,也可以读空格。输入字符串时,如果上一个输入结束后有回车,并且没有用getchar吃掉的话,gets函数就会读入回车,而不会 读入字符串。
- getline函数,可以读入空格、回车。用法:string ch; getline(cin,ch);需要注意的是,输入的必须是string类型的,不能是char。
- cin函数不能读入空格。
- puts函数可以自动输出换行,输出字符串后自动换行,不用加’\n’。
343

被折叠的 条评论
为什么被折叠?



