算法竞赛入门经典第五章习题

注:以下代码均已ac,都是我自己敲的,仅供参考。如果有不合理的地方欢迎指正,如果有更好的方法欢迎交流。

一些实用的
Priority_queue set map 等使用struct类型时,必须重载<号。
定义模板如下:
struct node
{
    int a,b;
    node(int x = 0,int y = 0):a(x),b(y){}
    bool operator<(const node& rhs) const
    {
        if ( a == rhs.a ) return b > rhs.b; //b越小优先级越高
        else return a < rhs.a; //a越大优先级越高
    }
};

Proirity_queue
1、优先队列默认数越大,优先级越高,是大根堆
2、若想维护小根堆,priority_queue< int , vector<int> , greater<int> > q
3、优先队列使用 struct 重载<

Set
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
Set_union( ALL(x1) , ALL(x2) , INS(x) ); vector x为 x1和x2的并集
Set_intersection( ALL(x1) , ALL(x2) , INS(x) ); vector x为 x1和x2的交集


1、 Uva 1593
题意:输入若干行代码,使得各行的第i个单词都是左对齐的,而且单词之间至少有一个空格,输出对齐后的代码。

思路:用一个len[i]表示所有行代码中第i个单词的最长长度,这样输出每一行的第i个单词时就以len[i]为标准。输出时,先输出当前单词,若当前单词不为一行中最后一个然后用空格补足长度至len[i]+1(考虑与下一个单词之间的空格

#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <sstream>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))


string str[1008][181];
int len[181];
int column[1009];
int row;
string temp;

string s;
string buf;

int main()
{
    row = 0;
    Clean(len,0);
    while( getline(cin,temp) )
    {
        row++;
        int num = 0;
        stringstream ss(temp);
        while(ss>>buf)
        {
            num++;
            str[row][num] = buf;
            len[num] = max(len[num],(int)buf.length());
        }
        column[row] = num;
    }
    rep(i,1,row)
    {
        rep(j,1,column[i])
        {
            cout<<str[i][j];
            if ( j == column[i] ) break;
            rep(k, 1 , (int)(len[j]+1-str[i][j].length()) ) putchar(' ');
        }
        puts("");
    }
    return 0;
}

2、 Uva 1594

题意:有一个n元组,变化到下一个状态时a[i]为上一个状态的a[i+1]-a[i](i=n时为a[1]-a[n]),一直变化问会循环还是变成n0,最多一千步就能得到答案。3<=N<=15

思路:可以考虑用map判重,循环一千次,如果当前状态重复了或者为全零就跳出循环输出。用struct类型作mapkey时要重载<号。

(这里说要么会循环,要么会变为全零,也可以循环一千步,只判零,如果最后没有出现全零那一定是循环,这样写起来会简单一些)


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <map>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007

struct node
{
    int a[20];
    int tot;
    void change()
    {
        int temp = a[1];
        rep(i,1,tot-1) a[i] = abs( a[i+1] - a[i] );
        a[tot] = abs( temp - a[tot] );
    }
    bool operator < (const node t) const
    {
        rep(i,1,tot)
            if ( a[i] != t.a[i] ) return a[i]<t.a[i];
        return false;
    }
};

bool check(node t,int n)
{
    rep(i,1,n) if ( t.a[i]!=0 ) return false;
    return true;
}

int n;
map<node,int> flag;
node x;

int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        cin>>n;
        flag.clear();
        x.tot = n;
        rep(i,1,n)  cin>>x.a[i];
        rep(i,1,1000)
        {
            if ( flag[x] || check(x,n) ) break;
            flag[x] = 1;
            x.change();
        }
        if ( check(x,n) )
            puts("ZERO");
        else
            puts("LOOP");

    }
    return 0;
}


3、 Uva 10935

题意:有n张牌,每次把第一张丢掉,把第二张放到牌底,反复操作直至剩一张牌。按顺序输出丢掉牌的序号,和最后一张剩余牌的序号。

思路:很明显是用队列来模拟一下。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

int n;

int main()
{
    while(cin>>n)
    {
        bool out = false;
        if ( !n ) break;
        queue<int> q;
        rep(i,1,n) q.push(i);
        printf("Discarded cards:");
        while( q.size() > 1 )
        {
            if ( out ) putchar(',');
            out = true;
            cout<<" "<<q.front();
            q.pop();
            int t = q.front();
            q.pop();
            q.push(t);
        }
        puts("");
        cout<<"Remaining card: "<<q.front()<<endl;
    }
    return 0;
}

4、 uva 10763

题意:有n个学生想交换学习,如果一个人想从A校到B校,就必然要有一个人从B校到A校,给出每个人的信息,问这n个人能不能都交换成功。

思路:如果一个二元组(x,y)表示从x校到y校的学生数量,那么对于所有的二元组,且(y,x) = (x,y) 都成立,这些学生才能交换成功。可以用map来统计pair<int,int>,最后判断一下。 

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <map>
#include <utility>

using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))
#define mp make_pair

const int maxn = 500005;

int n;
int x[maxn];
int y[maxn];

map< pair<int,int> , int > flag;

bool check()
{
    if ( n & 1 ) return false;
    rep(i,1,n)
        if ( flag[ mp( x[i] , y[i] ) ] != flag[ mp( y[i] , x[i] ) ] ) return false;
    return true;
}

int main()
{
    while(cin>>n)
    {
        if ( !n ) break;
        flag.clear();
        rep(i,1,n)
        {
            scanf("%d%d",&x[i],&y[i]);
            flag[ mp(x[i],y[i]) ]++;
        }
        puts( check()?"YES":"NO");
    }
    return 0;
}

5、 uva 10391

题意:给出一个按字典序排好的词典,按照字典序顺序输出所有的复合词。复合词就是指这个单词是由给出词典的两个单词连接合成的。N<=12W

思路:首先我们把所有的单词都丢进map里,然后按照输入顺序判断每个单词是否是复合词。判断方法是枚举这个单词断开的位置,分成两个单词,然后在map检查一下这两个单词是否出现过。


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

map<string,int> flag;
string str[120009],temp;
int n = 0;

bool check(string t)
{
    string tx,ty;
    int len = t.length();
    rep(i,1,len-1)
    {
        tx = string( &t[0],&t[i] );
        ty = string( &t[i],&t[len] );
        if ( flag[tx] && flag[ty] ) return true;
    }
    return false;
}

int main()
{
    flag.clear();
    while(cin>>temp)
    {
        str[++n] = temp;
        flag[temp] = 1;
    }
    rep(i,1,n)
        if ( check(str[i]) ) cout<<str[i]<<endl;
    return 0;
}

6、 Uva 1595

题意:给出n个点,是否能找到一条竖线,使得这n个点关于这条线对称。

思路:记录n个点x的最大值和最小值。如果对称线x = mid存在,那么2*mid等于left+right,因为mid可能为小数,所以mid*2,判断就采取mid == left+right的方式,可以避免小数。用 pair<int,int> 表示点,然后丢进map。最后判断的时候对于每个不在对称线上的点,如果map(x,y) 都等于 对称点(mid-x,y),那么这n个点就是对称的。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>

using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define mp(x,y) make_pair(x,y)

const int maxn = 1009;

int n;
int L,R;
int mid;

map< pair<int,int> ,int> flag;
int x[maxn],y[maxn];


bool check()
{
    rep(i,1,n)
    {
        if ( 2*x[i]== mid )
        {
            continue;
        }
        if ( flag[ mp(x[i],y[i]) ] != flag[ mp( mid - x[i],y[i] ) ] ) return false;
    }
    return true;
}
int T;

int main()
{
    cin>>T;
    while(T--)
    {
        cin>>n;
        flag.clear();
        rep(i,1,n)
        {
            scanf("%d %d",&x[i],&y[i]);
            flag[ mp(x[i],y[i]) ]++;
        }
        L = x[1];
        R = x[1];
        rep(i,2,n)
        {
            L = min(L,x[i]);
            R = max(R,x[i]);
        }
        mid = L+R;
        puts( check()?"YES":"NO");
    }

    return 0;
}

7、 uva 12100

题意:有一个打印机,有一些任务在排着队打印,每个任务都有优先级。打印时,每次取出队列第一个任务,如果它的优先级不是当前队列中最高的,就会被放到队尾,否则就打印出来。输出初始队列的第m个任务的打印时间,每次打印花费单位1的时间。

思路:用队列模拟一下。建一个<num,pos>的队列qnum表示优先级,pos表示位置。然后再按照优先级建一个优先队列pq

每次先把q的队首拿出来

(1)不是当前优先级最高的,num<pq.top(),再把出队的这个元素push回去。

(2)是当前优先级最高的,num==pq.top()
如果pos == m ,输出结束。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

int T;
int n,m,temp;

struct node
{
    int num,pos;
    node(int x = 0,int y = 0)
    {
        num = x;
        pos = y;
    }
};
int main()
{
    cin>>T;
    while(T--)
    {
        queue<node> q;
        priority_queue<int> pq;
        cin>>n>>m;
        rep(i,0,n-1)
        {
            scanf("%d",&temp);
            q.push(node(temp,i));
            pq.push(temp);
        }
        int t;
        node x;
        int ans = 0;
        while(1)
        {
            x = q.front();
            t = pq.top();
            q.pop();
            if ( t == x.num )
            {
                pq.pop();
                ans++;
                if ( x.pos == m )
                {
                    cout<<ans<<endl;
                    break;
                }
            }
            else    q.push(x);
        }
    }
    return 0;
}

8、Uva 230

题意:图书馆有一些书。可以执行借书、还书操作,还有一个操作是输出当前还回来的书应该放到架子上的哪个位置。具体细节可以去看原题。

思路:将每本书都用map对应一个编号。用一个vector来记录哪些书是还回来的。用一个set来记录当前书架上还剩下哪些书。

借书操作:set.earse(x)

还书操作:vector.push_back(x)

输出:将vector先排个序,然后一本一本的加回set里,再用set.lower_bound查找这本书的位置,根据情况输出即可。

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)

#define Clean(x,y) memset(x,y,sizeof(x))
const int maxn = 10009;
vector< pair<string,string> > book;
map<string,int> pos;
string a[maxn];
int num;
char temp[300];

set<int> now;
vector<int> Back;

int main()
{
    num = 0;
    book.clear();
    string author,title;
    while(1)
    {
        gets(temp);
        if ( temp[0] == 'E' && temp[1] == 'N' && temp[2] == 'D' ) break;
        num++;
        int len = strlen(temp);
        int k = strchr(temp+1,'"')-temp;
        title = string(&temp[1],&temp[k]);
        author = string(&temp[k+5],&temp[len]);
        book.push_back( make_pair(author,title) );
    }
    sort(book.begin(),book.end());
    rep(i,0,num-1)
    {
        a[i] = book[i].second;
        pos[ a[i] ]= i;
    }

    now.clear();
    rep(i,0,num-1) now.insert(i);
    Back.clear();
    while(1)
    {
        gets(temp);
        if ( temp[0] == 'E' ) break;
        else if ( temp[0] == 'S' )
        {
            set<int>::iterator k;
            sort(Back.begin(),Back.end());
            rep(i,0,(int)Back.size()-1 )
            {
                now.insert( Back[i] );
                k = now.lower_bound( Back[i] );
                if ( k == now.begin() ) cout<<"Put \""<<a[Back[i]]<<"\" first"<<endl;
                else
                {
                    k--;
                    cout<<"Put \""<<a[Back[i]]<<"\" after \""<< a[ *k ] <<"\""<<endl;
                }
            }
            Back.clear();
            puts("END");
        }
        else
        {
            int k = strchr(temp,'"')-temp;
            title = string(&temp[k+1],&temp[strlen(temp)-1]);
            k = pos[title];
            if ( temp[0] == 'B' ) now.erase(k);
            else Back.push_back(k);
        }
    }
    return 0;
}

9、Uva 1596

题意:给出一段程序,输出第一个出现bug的位置。

程序有两个格式:一种是定义一个数组,并规定数组大小;一种是对数组元素进行赋值。 

Bug有两种:一种是数组越界,一种是使用未初始化的变量。

思路:模拟判断

如果是第一种语句,就给丢进map给个编号并记录数组大小。

第二种语句用递归判断一下,因为可以嵌套类似这样a[a[1]]

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;

#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))

const int maxn = 1001;

char temp[100];
string str;

int ans;
int arraynum;

map<string,int> pos;      //为数组名编号
map<int,int> value[maxn]; //每个数组的值是多少
map<int,bool> flag[maxn]; //每个数组的值是否被初始化
int ind[maxn]; // 最大下标

int getnum(char* st,char *ed)
{
    int ans = 0;
    for(char *i = st;i<=ed;i++)
        if ( isdigit( *i ) ) ans = ans * 10 + *i - '0';
        else break;
    return ans;
}

int getvalue(char *st,char *ed,bool& f)
{
    if ( !f ) return 0;
    char *s = st;
    int ans;
    if ( isdigit( *s ) )
        ans = getnum(st,ed);
    else
    {
        int k = strchr(st,'[') - st;
        string arrayname = string(st,st+k);
        int Ind = getvalue( st+k+1,ed,f );
        k = pos[arrayname];
        if( Ind< ind[ k ] && flag[ k ][Ind]  )
            ans = value[k][Ind];
        else
        {
            f = false;
            ans = 0;
        }
    }
    return ans;
}

bool init()
{
    gets(temp);
    if ( temp[0] == '.' ) return false;
    arraynum = 0;
    ans = 0;
    bool ok = true;
    while( temp[0]!='.' )
    {
        if ( ok )
        {
            if ( strchr(temp,'=') == NULL )
            {
                arraynum++;
                flag[arraynum].clear();
                value[arraynum].clear();
                int k = strchr(temp,'[') - temp;
                str = string(&temp[0],&temp[k]);
                pos[str] = arraynum;
                ind[arraynum] = getnum(temp+k+1,temp+strlen(temp)-1);
            }
            else
            {
                string arrayname;
                int Ind;
                int Val;
                bool vaild = true;
                int k = strchr(temp,'[') - temp;
                arrayname = string(&temp[0],&temp[k]);
                int p = strchr(temp,'=') - temp;
                Ind = getvalue(temp+k+1,temp+p,vaild);
                Val = getvalue(temp+p+1,temp+strlen(temp)-1,vaild);
                k = pos[arrayname];
                if ( !vaild || Ind>=ind[k] ) ok = false;
                else
                {
                    flag[k][Ind] = true;
                    value[k][Ind] = Val;
                }
            }
            ans++;
        }
        gets(temp);
    }
    if ( ok ) ans = 0;
    return true;
}

int main()
{
    while( init() )
    {
        cout<<ans<<endl;
    }
    return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值