编程题#1
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 1000ms 内存限制: 65536kB
描述
下面的程序输出结果是:
1 2 6 7 8 9
请填空:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main() {
int a[] = {8,7,8,9,6,2,1};
// 在此处补充你的代码
ostream_iterator<int> o(cout," ");
copy( v.begin(),v.end(),o);
return 0;
}
输入
无
输出
1 2 6 7 8 9
样例输入
1
无
样例输出
1
1 2 6 7 8 9
#include <iostream>
#include <iterator>
#include <set>
#include <list>
using namespace std;
int main() {
int a[] = { 8,7,8,9,6,2,1 };
// 在此处补充你的代码
//list<int> v(a, a + 7);
//v.sort();
//v.unique();
set<int> v(a, a + 7);
ostream_iterator<int> o(cout, " ");
copy(v.begin(), v.end(), o);
return 0;
}
编程题#1 List
来源: POJ (Coursera声明:在POJ上完成的习题将不会计入Coursera的最后成绩。)
注意: 总时间限制: 4000ms 内存限制: 65536kB
描述
写一个程序完成以下命令:
new id ——新建一个指定编号为id的序列(id<10000)
add id num——向编号为id的序列加入整数num
merge id1 id2——合并序列id1和id2中的数,并将id2清空
unique id——去掉序列id中重复的元素
out id ——从小到大输出编号为id的序列中的元素,以空格隔开
输入
第一行一个数n,表示有多少个命令( n<=200000)。以后n行每行一个命令。
输出
按题目要求输出。
样例输入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
16
new 1
new 2
add 1 1
add 1 2
add 1 3
add 2 1
add 2 2
add 2 3
add 2 4
out 1
out 2
merge 1 2
out 1
out 2
unique 1
out 1
样例输出
#include<iostream>
#include<list>
#include <iterator>
#include<vector>
#include<string>
using namespace std;
int GetNum(string &s)//用来读取命令后面的数字的,包括id和num
{
int pos = s.rfind(" ");//反向查找
string num = s.substr(pos + 1, s.length() - 1 - pos);
s.erase(pos);
return stoi(num);//把数字字符串转换成int输出
}
int main()
{
//以下两行是用来读取和输出测试数据的
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int n;
cin >> n;
cin.get();//吃回车
vector<string> command(n);//string类的vector
string tmp;
for (int i = 0; i < n; i++)
{
getline(cin, tmp);
command[i] = tmp;
}
vector<list<int>> lst(10000);
for (int i = 0; i < n; i++)//判断是否是add命令
{
if (command[i].at(0) == 'a')
{
int num = GetNum(command[i]);
int id = GetNum(command[i]);
lst[id - 1].push_back(num);
}
else if (command[i].at(0) == 'm')//判断是否是merge命令
{
int id2 = GetNum(command[i]);
int id1 = GetNum(command[i]);
lst[id1 - 1].merge(lst[id2 - 1]);
}
else if (command[i].at(0) == 'u')//判断是否是unique命令
{
int id = GetNum(command[i]);
lst[id - 1].sort();
lst[id - 1].unique();
}
else if (command[i].at(0) == 'o')//判断是否是out命令
{
int id = GetNum(command[i]);
lst[id - 1].sort();
ostream_iterator<int> o(cout, " ");
copy(lst[id - 1].begin(), lst[id - 1].end(), o);
cout << endl;
}
}
return 0;
}