2020年2月27日 PAT

A1050 20’ 8min 散列 easy

  • 循环里的判断不要写i<strlen(str) 因为这个函数本身时间复杂度就是O(N),在循环一次时间复杂度间变成了O(N2)
    在这里插入图片描述
#include <iostream>
#include <string>
using namespace std;
void test()
{
	string a,b;
	getline(cin,a);
	getline(cin,b);
	int hash[128] = { 0 };
	int lena = a.size();
	int lenb = b.size();
	for (int i = 0; i < lenb; ++i)
	{
		hash[b[i]] = 1;
	}
	for (int i = 0; i < lena; ++i)
	{
		if (hash[a[i]] == 0)
			cout << a[i];
	}
}
int main()
{
	test();
	system("pause");
	return 0;
}

B1005 25’ 散列 ‘easy’

  • set 从大到小排 用for(auto i = rend(); i!=rbegain(); ++i) 可以倒序遍历
  • set默认从小到大排序
  • set没有下标访问运算符
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b)
{
	return a > b;
}
void test()
{
	int n,m;
	vector<int> sets;
	int hash[10000] = {0};
	cin >> m;
	for (int i = 0; i < m; ++i)
	{
		cin >> n;
		sets.push_back(n);
		while (n != 1)
		{
			if (n % 2 == 1)
			{
				n = (n * 3 + 1) / 2;
				hash[n] = 1;
			}
			if (n % 2 == 0)
			{
				n /= 2;
				hash[n] = 1;
			}
		}
	}
	int len = sets.size();
	sort(sets.begin(),sets.end(),cmp);
	int flag = 1;
	for (int i=0;i<len;++i)
	{
		if (hash[sets[i]] != 1&&flag==1)
		{
			printf("%d", sets[i]);
			flag = 0;
			continue;
		}	
		if (hash[sets[i]] != 1 && flag == 0)
		{
			printf(" %d", sets[i]);
		}
	}
}
int main()
{
	test();
	system("pause");
	return 0;
}

A1048 25’ 散列 medium有一些知识点没掌握

#include <iostream>
using namespace std;
void test()
{
	int n, m, s;
	int a[1005] = {0};
	cin >> n >> m;
	while (n--)
	{
		cin >> s;
		a[s]++;
	}

	//cout << a[1] << 11111;
	/*
	当输入
	
	1 1
	1
	
	就无法输出no solution
	
	*/
	for (int i = 0; i < 1005; i++)
	{
		if (a[i] && a[m - i])//1 1 这个例子无法通过if 最后啥也不输出 而原本应该输出no solution
		{
			if (i == m - i&&a[i] > 1)
			{
				cout << i << " " << m - i;
				break;
			}
			else if (i == m - i&&a[i] == 1)
			{
				cout << "No Solution";
				break;
			}
			else
			{
				cout << i << " " << m - i;
				return ;
			}
		}
	}
}
int main()
{
	test();
	system("pause");
	return 0;
}

AC代码

  • 数组定义在全局变量
    • 默认初始化为0 a[-1]也是0
  • 函数体内的默认初始化
    • 默认为乱码
    • a[10]={0} 则a[-1]=乱码 在if那里造成bug
#include <iostream>
using namespace std;
 int a[1005];//写在函数体内a[1005]={0} 就不对了
void test()
{
	int n, m, s;
	cin >> n >> m;
	while (n--)
	{
		cin >> s;
		++a[s];
	}
	for (int i = 0; i < 1005; i++)
	{
		if(a[i]&&a[m-i])//数组写在函数体内会使一些错误input进入if语句造成Bug
        {
            if(i==m-i&&a[i]<=1)
                continue;
            cout << i << " " << m-i;
            return ;
        }
	}
    cout << "No Solution";
}
int main()
{
    test();
	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值