《算法竞赛入门经典》第五章C++与STL入门书上例题

44 篇文章 1 订阅
7 篇文章 0 订阅

排序与检索

大理石在哪儿(Where is the Marble? UVa 10474)

题目描述
现有N各大历史,每个大理石上写了一个非负整数。首先把各数从小到大排序,然后回答Q个问题。每个问题问是否有一个大理石上写着某个整数x,如果是,还要回答哪个大理石上写着x。排序后的大理石从左到右编号为1~N。

样例输入:
4 1
2 3 5 1
5
5 2
1 3 3 3 1
2
3
样例输出:
CASE# 1:
5 found at 4
CASE# 2:
2 not found
3 found at 3

#include <cstdio>
#include <algorithm>
using namespace std;

const int maxn = 10000;

int main() {
    int n, q, x, a[maxn], kase = 0;
    while (scanf("%d%d", &n, &q) == 2 && n) {
        printf("CASE# %d:\n", ++kase);
        for (int i = 0; i < n; i++) 
            scanf("%d", &a[i]);
        sort(a, a+n);  
        while (q--) {
            scanf("%d", &x);
            int p = lower_bound(a, a+n, x) - a;    //lower_bound的作用是查找大于或者等于x的第一个位置
                                                   // 数组地址相减结果为相差的元素个数 
            if (a[p] == x)
                printf("%d found at %d\n", x, p+1);
            else
                printf("%d not found\n", x);
        }
    }
    return 0;
} 

不定长数组:vector

木块问题(The Blocks Problem, UVa 101)

题目描述
从左到右有n个木块,编号为0~n-1,要求模拟以下四种操作(下面的a和b都是木块编号)。

  • move a onto b:把a和b上方的木块全部归位,然后把a摞在b上面。
  • move a over b:把a上方的木块全部归位,然后把a放在b所在木块堆的顶部
  • pile a onto b:把b上方的木块全部归位,然后把a及上面的木块整体摞在b上面。
  • pile a over b:把a及上面的木块整体摞在b所在木块堆的顶部。
#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;

const int maxn = 30;
int n; 
vector<int> pile[maxn];     // 每个pile[i]是一个vector 
// 找木块a所在的pile和height,以引用的形式返回调用者
void find_block(int a, int &p, int &h) {
    for (p = 0; p < n; p++) {
        for (h = 0; h < pile[p].size(); h++) {
            if (pile[p][h] == a)
                return;
        }
    }
} 
// 把第p堆高度为h的木块上方的所有木块归回原位
void clear_above(int p, int h) {
    for (int i = h+1; i < pile[p].size(); i++) {
        int b = pile[p][i];
        pile[b].push_back(b);    // 把木块b放回原位 
    }
    pile[p].resize(h+1);  // pile只应保留下标0~h的元素 
} 
// 把第p堆高度为h及其上方的木块整体移动到p2堆的顶部
void pile_onto(int p, int h, int p2) {
    for (int i = h; i < pile[p].size(); i++) {
        pile[p2].push_back(pile[p][i]);
    }
    pile[p].resize(h);
} 
void print() {
    for (int i =0; i < n; i++) {
        printf("%d: ", i);
        for (int j = 0; j < pile[i].size(); j++) {
            printf(" %d", pile[i][j]);
        }
        printf("\n");
    }
}
int main() {
    int a, b;
    cin >> n;
    string s1, s2;
    for (int i = 0; i < n; i++) {
        pile[i].push_back(i);
    }
    while (cin >> s1 >> a >> s2 >> b) {
        int pa, pb, ha, hb;
        find_block(a, pa, ha);
        find_block(b, pb, hb);
        if (pa == pb)
            continue;   // 非法指令
        if (s2 = "onto")
            clear_above(pb, hb);
        if (s1 == "move")
            clear_above(pa, ha);
            pile_onto(pa, ha, pb);
    }
    printf();
    return 0;
} 

集合:set

安迪的第一个字典(Andy’s First Dictionary, UVa 10815)

题目描述
输入一个文本,找出所有不同的单词(连续的字母序列),按字典序从小到大输出。单词不区分大小写。

样例输入:
Adventures in Disneyland
Two blonedes were going to Dieneyland when they came to a fork in the road.The sign read :”Disneyland left.”
So they went home.
样例输出(为了节约篇幅只保留前五行):
a
adventure
blondes
came
disneyland

#include <sstream>
#include <iostream>
#include <set>
#include <string>
using namespace std;
set<string> dict;    // string集合

int main() {
    string s, buf;
    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);    // stringstream把' '当做串分隔符,以此可以去掉标点符号 
        while (ss >> buf)
            dict.insert(buf);
    }
    for(set<string>::iterator it = dict.begin(); it != dict.end(); it++) {
        cout << *it << endl;
    }
    return 0;
} 

映射:map

反片语(Ananagram, UVa 156)

题目描述
输入一些单词,找出所有满足如下条件的单词:该单词不能通过字母重排,得到输入文本的另外一个单词。在判断是否满足条件时,字母不分大小写,但是在输出时应保留输入中的大小写,按字典序进行排列(所有大写字母在所有小写字母的前面)。

样例输入:
ladder came tape soon leader acme RIDE lone Dreis peat scAlE orb eye rides dealer NotE derail LaCeS drIed noel dire Disk mace Rob dries
样例输出:
Disk
NotE
derail
drIed
eye
ladder
soon

#include <cctype>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
map<string, int> cnt;
vector<string> words;
//讲单词进行“标准化”
string repr(const string& s) {
    string ans = s;
    for (int i = 0; i < s.length(); i++) {
        ans[i] = tolower(ans[i]);
    }
    sort(ans.begin(), ans.end());    // c++中字符串有begin()和end()属性,是指针 
    return ans;
} 

int main() {
    int n = 0;
    string s;
    while (cin >> s) {
        if (s[0] == '#')
            break;
        words.push_back(s);
        string r = repr(s);
        if (!cnt.count(r))
            cnt[r] = 0;
        cnt[r]++;
    }
    vector<string> ans;
    for (int i = 0; i < words.size(); i++) {
        if(cnt[repr(words[i])] == 1)
            ans.push_back(words[i]);
    }
    sort(ans.begin(),ans.end());
    for (int i = 0; i < ans.size(); i++) {
        cout << ans[i] << endl;
    }
    return 0;
} 

栈、队列与优先队列

集合栈计算机(The SetStack Computer,CM/ICPC NWERC 2006, UVa 12096)

题目描述
有一个专门为了集合运算而设计的“集合栈”计算机。该机器有一个初始为空的栈,并且支持以下操作:

  • PUSH:空集“{}”入栈。
  • DUP:把当前栈顶元素复制一份后再入栈。
  • UNION:出栈两个集合,然后把二者的并集入栈。
  • INTERSECT:出栈两个集合,然后把二者的交集入栈。
  • ADD:出栈两个集合,然后把先出栈的集合加入到后出栈的集合中,把结果入栈。

每次操作后,输出栈顶集合的大小(即元素个数)。例如,栈顶元素是A = { {}, {{}} },下一个元素是B = { {}, {{{}}} },则:

  • UNION操作将得到{ {}, {{}}, {{{}}} },输出3
  • INTERSECT操作将得到{ {} },输出1
  • ADD 操作将得到{ {}, {{{}}} , { {}, {{}} } },输出3

输入不超过2000个操作,并且保证操作均能顺利进行(不需要对空栈执行出栈操作)。
分析
本体的集合并不是简单的整数集合或者字符串集合,而是集合的集合。为了方便起见,此处为每个不同的集合分配一个唯一的ID,则每个集合可以表示成所包含元素的ID的集合,这样就可以用STL的set<int>来表示了,而整个栈则是一个stack<int>

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <set> 
#include<stack>
#include <algorithm>
using namespace std;
typedef set<int> Set;
map<Set, int> IDcache;    // 把集合映射成ID
vector<Set> Setcache;     // 根据ID取集合 

// 查找给定集合x的ID,如果找不到,则分配一个新ID
int ID (Set x) {
    if (IDcache.count(x))
        return IDcache[x];
    Setcache.push_back(x);   // 添加新集合
    return IDcache[x] = Setcache.size() - 1; 
} 

#define ALL(x) x.begin(), x.end()
#define INS(x) inserter(x, x.begin())
int main() {
    stack<int> s;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        string op;
        cin >> op;
        if (op[0] == 'P') 
            s.push(ID(Set()));

        else if (op[0] == 'D')
            s.push(s.top());
        else {
            Set x1 = Setcache[s.top()];
            s.pop();
            Set x2 = Setcache[s.top()];
            s.pop();
            Set x;
            if (op[0] == 'U')
                set_union(ALL(x1), ALL(x2), INS(x));
            if (op[0] == 'I')
                set_intersection(ALL(x1), ALL(x2), INS(x));
            if (op[0] == 'A') {
                x = x2;
                x.insert(ID(x)); 
            } 
        }
        cout << Setcache[s.top()].size() << endl;
    }
    return 0;
} 
团体队列(Team Queue, UVa 540)

题目描述
有t个团队的人正在排一个长队。每次新来一个人的时候,如果他有队友在排队,那么这个新人会插入到最后一个队友的身后。如果没有任何一个队友排队,则他会排到长队的队尾。
输入每个团队中所有队员的编号,要求支持如下3种指令(前面两种指令可以穿插进行)。

  • ENQUEUE x:编号为x的人进入长队。
  • DEQUEUE:长队的队首出队。
  • STOP:停止模拟。
    对于每个DEQUEUE指令,输出出队的人的编号。

分析
本题有两个队列,每个团队有一个队列,而团队整体又形成一个队列。例如,有3个团队1,2,3,队员集合分别为{101,102,103,104}、{201,201}和{301,302,303},当前长队为{301,303,103,101,102,201},则3个团队的队列分别为{103,102,101}、{201}和{301,303},而团队整体的队列为{3,1,2}。

#include <cstdio>
#include <queue>
#include <map>
using namespace std;
const int maxt = 1000 + 10;
int main() {
    int t, kase = 0;
    while (scanf("%d", &t) == 1 && t) {
        printf("Scenario #%d\n", ++kase);
        //记录所有人的团队的编号
        map<int, int> team;   //team[x]表示编号为x的人所在的团队编号 
        for (int i = 0; i < t; i++) {   // 队伍数 
            int n, x;
            scanf("%d", &n);       // 队伍中人数 
            while (n--) {
                scanf("%d", &x);   // 输入编号 
                team[x] = i;
            }
        }
        // 模拟
        queue<int> q, q2[maxt];    // q是团队的队列,而q2[i]是团队i成员的队列 
        for (;;) {
            int x;
            char cmd[10];
            scanf("%s", cmd);
            if (cmd[0] == 'S')
                break;
            else if (cmd[0] == 'D') {
                int t = q.front();
                printf("%d\n", q2[t].front());
                q2[t].pop();
                if (q2[t].empty())
                    q.pop();     // 团队t全体出列 
            }
            else if (cmd[0] == 'E') {
                scanf("%d", &x);
                int t = team[x];
                if (q2[t].empty())
                    q.push(t);    // 团队t进入队列 
                q2[t].push(x); 
            } 
        } 
        printf("\n");
    }
    return 0;
} 
丑数(Ugly Numbers, UVa 136)

题目描述
丑数是指不能被2,3,5以外的其他素数整除的数。把丑数从小到大排列起来,结果如下:
1,2,3,4,5,6,8,9,10,12,15,…
求第1500个丑数。

#include <iostream>
#include <queue>
#include <vector>
#include <set>
using namespace std;
typedef long long LL;
const int coeff[3] = {2, 3, 5};

int main() {
    priority_queue<LL, vector<LL>, greater<LL> > pq;
    set<LL> s;
    pq.push(1);
    for (int i = 1; ; i++) {
        LL x = pq.top();
        pq.pop();
        if (i == 1500) {
            cout << "The 1500'th ugly number is " << x << ".\n";
            break;
        }
        for (int j = 0; j < 3; j++) {
            LL x2 = x * coeff[j];
            if (!s.count(x2)) {
                s.insert(x2);
                pq.push(x2);
            }
        }
    }
    return 0;
} 

竞赛题目举例

城市正视图(Urban Elevations, ACM/ICPC World Finals 1992, UVa221)

题目描述
如图所示,有n(n<=100)个建筑物。左侧是俯视图(左上角为建筑物编号,右下角为高度),右侧是从南向北看的正视图。
这里写图片描述
输入每个建筑物左下角坐标(即x,y坐标的最小值)宽度(即x方向的长度)、深度(即y方向的深度)和高度(以上数据均为实数),输出正视图中能看到的所有建筑物,按照左下角x坐标从小到大进行排序。左下角x坐标相同时,按y坐标从小到大排序。

#include <cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100 + 5;
struct Building {
    int id;
    double x, y, w, d, h;
     // 建筑物a的x比建筑物b的小或x相等y小,则a在b前 
    bool operator < (const Building& rhs) const {
        return x < rhs.x || (x == rhs.x && y < rhs.x); 
    }
} b[maxn];
int n;
double x[maxn*2];   // 保存所有建筑物的左x和右x 
// 某点是否在建筑物i的左右范围内 
bool cover (int i, double mx) {
    return b[i].x <= mx && b[i].x + b[i].x + b[i].w >= mx;
}
/*  判断建筑物i在x=mx处是否可见
    具体方法是:把所有x坐标排序去重,则任意两个相邻x坐标形成的区间具有相同属性,一个区间要么完全可见
    要么完全不可见。这样,只需在空间里任意选一点(例如中点),就能判断出一个建筑物是否在整个区间内是否可见。
    首先,建筑物的坐标中必须包含这个x坐标,其次,建筑物南边不能有另外一个建筑物也包含这个x坐标,并且不比它矮。 
*/
bool visible(int i, double mx) {
    if (!cover(i, mx))  // mx不在建筑物i的左右范围内 
        return false;

    for (int k = 0; k < n; k++) {
        if (b[k].y < b[i].y && b[k].h >= b[i].h && cover(k, mx))
            return false;
    } 
    return true;
} 
int main() {
    int kase = 0;
    while (scanf("%d", &n) ==1 && n) {
        for (int i = 0; i < n; i++) {
            scanf("%lf%lf%lf%lf%lf", &b[i].x, &b[i].y, &b[i].w, &b[i].d, &b[i].h);
            x[i*2] = b[i].x;
            x[i*2+1] = b[i].x + b[i].w;
            b[i].id = i + 1;
        }
        sort(b, b+n);    // 根据从左到右,从前到后的顺序排序
        sort(x, x+n*2);  // 根各x坐标排序
        int m = unique(x, x+n*2) - x;  // x坐标排序后去重,m为剩余的x坐标个数
        if (kase++)
            printf("\n");
        printf("For map #%d, the visible buildings are numbered as follows: \n%d", kase, b[0].id); // 排在最前的肯定可以被看到
        for (int i = 1; i < n; i++) {
            bool vis = false;
            for (int j = 0; j < m-1; j++) {
                if(visible(i, (x[j]+x[j+1])/2)) {
                    vis = true;
                    break;
                }
            }
            if (vis) {
            printf(" %d", b[i].id);
            }   
        } 
        printf("\n");
    }
    return 0;
} 
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值