P2141
珠心算测验
vector中unique函数的使用,从头到尾,判断当前元素是否等于上一个元素,将不重复的元素移到前面来(赋值操作),返回值:去重以后vector中没有重复元素的下一个位置的迭代器。因此要想去重,需要删除后面的元素。
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int>s;
unsigned long long count=0;
unsigned int i,j,n;
cin>>n;
int s0[n];
for(i=0;i<n;i++)
cin>>s0[i];
for(i=0;i<n;i++)
{
for( j=i+1;j<n;j++)
s.push_back((s0[i]+s0[j]));
}
sort(s.begin(),s.end());
s.erase(unique(s.begin(), s.end()), s.end());
for(i=0;i<n;i++)
{
for( j=0;j<s.size();j++)
{
if(s0[i]==s[j])
{
++count;
}
}
}
cout<<count;
return 0;
}
P1308
[NOIP2011 普及组] 统计单词数
string 中find函数用法,用于找出字母在字符串中的位置 position。如果查找的不是单个字符,返回的是字符串第一个字符的位置。可以不填第二个参数,默认从字符串的开头进行查找。当没有找到目标字符时返回npos,类型为string::size_type(一般可以看成unsigned int)。
find函数其他相关: rfind():查找子字符串或字符最后一次出现的位置。
find_first_of():顾名思义
find_last_of():顾名思义
find_first_not_of():返回在字符串中首次出现的不匹配str中的任何一个字符的首字符索引
find_last_not_of():顾名思义
#include <bits/stdc++.h>
using namespace std;
int main()
{
string a;
string b;
getline(cin, a);
getline(cin, b);
for (unsigned int i = 0; i < a.length(); ++i)
{
a[i] = tolower(a[i]);
}
for (unsigned int i = 0; i < b.length(); ++i)
{
b[i] = tolower(b[i]);
}
a = ' ' + a + ' ';
b = ' ' + b + ' ';
if (b.find(a) == string::npos)
{
cout << -1 << endl;
}
else
{
string::size_type alpha = b.find(a);
string::size_type beta = b.find(a), s = 0;
while (beta != string::npos)
{
++s;
beta = b.find(a, beta + 1);
}
cout << s << " " << alpha << endl;
}
return 0;
}
P1597
语句解析
scanf的返回值:返回已成功赋值的数据项数;出错时则返回EOF.
scanf格式输入非常方便。
#include <bits/stdc++.h>
using namespace std;
int a[3];
char s1, s2;
int main()
{
while (scanf("%c:=%c;", &s1, &s2) == 2)
a[s1 - 'a'] = s2 >= '0' && s2 <= '9' ? s2 - '0' : a[s2 - 'a'];
printf("%d %d %d", a[0], a[1], a[2]);
}