访问次数:

set练习题 | Wenji's blog
头部背景图片
WenJi's blog |
WenJi's blog |

set练习题

丑数 优先队列和set查重count练习

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
#include<queue>
#include<set>
using namespace std;
typedef long long ll;//此题易错是long long 不是int
int main()
{
ll n;
int factor[3]={2,3,5};
while(cin>>n&&n!=0)
{
priority_queue<ll,vector<ll>, greater<ll> > q1;
set<ll> q2;
q1.push(1);
q2.insert(1);
ll i;
for(i=1;;i++)
{
ll m1=q1.top();
q1.pop();
if(i==n)
{
printf("%lld\n",m1);
break;
}
for(int j=0;j<3;j++)
{
ll m2=m1*factor[j];
if(!q2.count(m2))
{
q1.push(m2);
q2.insert(m2);
}
}

}
}
return 0;
}

set对结构体排序的常见用法和排序插件cmp的用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<iostream>
#include<set>
#include<string>
#include<cstdio>
using namespace std;
struct Student
{
int id;
string name;
}stu1,stu2,stu3;
struct setcmp//set容器的插件,来确定set内部的排序
{
bool operator()(Student a,Student b)
{
return a.id>b.id; //这个大括号不可以省略,不然会报错的
}
};
struct Setcmp
{
bool operator()(Student a,Student b)
{
return a.id<b.id;
}
};
int main()
{
set<Student,setcmp> my;
set<Student>::iterator it;
stu1.id=1000;
stu2.id=2000;
stu3.id=3000;
stu1.name="ddd";
stu2.name="www";
stu3.name="aaa";
my.insert(stu1);
my.insert(stu2);
my.insert(stu3);
for(it=my.begin();it!=my.end();it++)
{
cout<<it->id<<" "<<it->name<<endl;
}
set<Student,Setcmp> mm;
mm.insert(stu1);
mm.insert(stu2);
mm.insert(stu3);
for(it=mm.begin();it!=mm.end();it++)
{
cout<<it->id<<" "<<it->name<<endl;
}
return 0;
}

uva10815 set练习以及输入流sstream中的stringstream

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string>
#include<sstream>
#include<set>
using namespace std;
int main()
{
set<string> str;
string s;
while(cin>>s)
{
for(int i=0;i<s.length();i++)
{
if(isalpha(s[i]))
{
s[i]=tolower(s[i]);
}
else
{
s[i]=' ';//一个字符空格时' '不是" "; 输入的非字符转换为空格,作为单词的分界点
}
}
stringstream ss(s);//流 ;
//构造时就写进,因为时对象的原因,将s加入ss流类里面,就类似于文件里面的输入文件一样
string s2;
while(ss>>s2)
{
str.insert(s2);
}
}
for(set<string>::iterator it=str.begin();it!=str.end();it++)
{
cout<<*it<<endl;
}
return 0;
}