PAT甲级1026~1050

1026 Table Tennis (30 分)

A table tennis club has N tables available to the public. The tables are numbered from 1 to N. For any pair of players, if there are some tables open when they arrive, they will be assigned to the available table with the smallest number. If all the tables are occupied, they will have to wait in a queue. It is assumed that every pair of players can play for at most 2 hours.
Your job is to count for everyone in queue their waiting time, and for each table the number of players it has served for the day.
One thing that makes this procedure a bit complicated is that the club reserves some tables for their VIP members. When a VIP table is open, the first VIP pair in the queue will have the privilege to take it. However, if there is no VIP in the queue, the next pair of players can take it. On the other hand, if when it is the turn of a VIP pair, yet no VIP table is available, they can be assigned as any ordinary players.

#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstdio>
using namespace std;

struct player{
    int come_time,play_time,serve_time=0,leave_time;
    int isvip;
};

struct table{
    int count=0,serve=-1;
    int isvip=0;
};

bool cmp(player x,player y){
    return x.come_time<y.come_time;
}

void printtime(int Time){
    printf("%02d:%02d:%02d ",Time/3600,Time%3600/60,Time%60);
}

player p[10000];
table t[101];
vector<int>y;

int main(){
    int N,K,M,i,j,k;
    char c;
    cin>>N;
    for(i=0;i<N;i++){
        int hh,mm,ss;
        cin>>hh>>c>>mm>>c>>ss>>p[i].play_time>>p[i].isvip;
        p[i].come_time=hh*3600+mm*60+ss;
        p[i].play_time*=60;
        if(p[i].play_time>7200)p[i].play_time=7200;
    }
    cin>>K>>M;
    while(M--){
        cin>>i;
        t[i].isvip=1;
    }
    sort(p,p+N,cmp);
    queue<int>q1,q2;
    int cursor=0;
    for(int Time=28800;Time<75600;Time++){
        for(i=1;i<=K;i++){
            if(t[i].serve>=0){
                j=t[i].serve;
                if(p[j].leave_time==Time){
                    t[i].serve=-1;
                }
            }
        }
        while(cursor<N&&p[cursor].come_time==Time){
            q1.push(cursor);
            if(p[cursor].isvip)q2.push(cursor);
            cursor++;
        }
        while(q2.size()&&p[q2.front()].serve_time!=0){
            q2.pop();
        }
        for(i=1;i<=K;i++){
            if(!t[i].isvip)continue;
            if(t[i].serve<0){
                if(q2.size()){
                    j=q2.front();
                    y.emplace_back(j);
                    t[i].serve=j;
                    t[i].count++;
                    p[j].serve_time=Time;
                    p[j].leave_time=Time+p[j].play_time;
                    while(q2.size()&&p[q2.front()].serve_time!=0){
                        q2.pop();
                    }
                }
            }
        }
        
        while(q1.size()&&p[q1.front()].serve_time!=0){
            q1.pop();
        }
        for(i=1;i<=K;i++){
            if(t[i].serve<0){
                if(q1.size()){
                    j=q1.front();
                    y.emplace_back(j);
                    t[i].serve=j;
                    t[i].count++;
                    p[j].serve_time=Time;
                    p[j].leave_time=Time+p[j].play_time;
                    while(q1.size()&&p[q1.front()].serve_time!=0){
                        q1.pop();
                    }
                }
            }
        }
    }
    
    for(int each:y){
        printtime(p[each].come_time);
        printtime(p[each].serve_time);
        cout<<(p[each].serve_time-p[each].come_time+30)/60;
        cout<<endl;
    }
    for(i=1;i<=K;i++){
        cout<<t[i].count;
        if(i<K)cout<<" ";
    }
}

1027 Colors in Mars (20 分)

People in Mars represent the colors in their computers in a similar way as the Earth people. That is, a color is represented by a 6-digit number, where the first 2 digits are for Red, the middle 2 digits for Green, and the last 2 digits for Blue. The only difference is that they use radix 13 (0-9 and A-C) instead of 16. Now given a color in three decimal numbers (each between 0 and 168), you are supposed to output their Mars RGB values.

#include<iostream>
using namespace std;

void print(int a){
    if(a>9)cout<<(char)('A'+a-10);
    else cout<<a;
}

int main(){
    cout<<"#";
    for(int i=0;i<3;i++){
        int a;
        cin>>a;
        print(a/13);
        print(a%13);
    }
}

1028 List Sorting (25 分)

Excel can sort records according to any column. Now you are supposed to imitate this function.

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<string.h>
using namespace std;

struct student{
    int id;
    char name[10];
    int grade;
};

bool cmp1(student&x,student&y){
    return x.id<y.id;
}

bool cmp2(student&x,student&y){
    int i=strcmp(x.name,y.name);
    if(i!=0)return i<0;
    else return x.id<y.id;
}

bool cmp3(student&x,student&y){
    if(x.grade!=y.grade)return x.grade<y.grade;
    else return x.id<y.id;
}

student s[100000];

int main(){
    int n,c;
    cin>>n>>c;
    int i=0;
    for(i=0;i<n;i++){
        scanf("%d",&s[i].id);
        scanf("%s",s[i].name);
        scanf("%d",&s[i].grade);
    }
    if(c==1)sort(s,s+n,cmp1);
    else if(c==2)sort(s,s+n,cmp2);
    else if(c==3)sort(s,s+n,cmp3);
    
    for(int j=0;j<n;j++){
        printf("%06d %s %d\n",s[j].id,s[j].name,s[j].grade);
    }
}

1029 Median (25 分)

Given an increasing sequence S of N integers, the median is the number at the middle position. For example, the median of S1 = { 11, 12, 13, 14 } is 12, and the median of S2 = { 9, 10, 15, 16, 17 } is 15. The median of two sequences is defined to be the median of the nondecreasing sequence which contains all the elements of both sequences. For example, the median of S1 and S2 is 13.
Given two increasing sequences of integers, you are asked to find their median.

方法一:vector

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main(){
    vector<int>v;
    int i,j,k;
    cin>>j;
    while(j--){
        scanf("%d",&i);
        v.emplace_back(i);
    }
    cin>>j;
    while(j--){
        scanf("%d",&i);
        v.emplace_back(i);
    }
    sort(v.begin(),v.end());
    cout<<v[(v.size()-1)/2];
}

方法二:归并排序

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

int a1[200000],a2[200000],c[400000];

int main(){
    int i1,i2,j1,j2,k;
    cin>>j1;
    for(i1=0;i1<j1;i1++){
        scanf("%d",a1+i1);
    }
    cin>>j2;
    for(i2=0;i2<j2;i2++){
        scanf("%d",a2+i2);
    }
    for(i1=i2=k=0;i1<j1&&i2<j2;){
        if(a1[i1]<a2[i2])c[k++]=a1[i1++];
        else c[k++]=a2[i2++];
    }
    while(i1<j1)c[k++]=a1[i1++];
    while(i2<j2)c[k++]=a2[i2++];
    cout<<c[(j1+j2-1)/2];
}

1030 Travel Plan (30 分)

A traveler’s map gives the distances between cities along the highways, together with the cost of each highway. Now you are supposed to write a program to help a traveler to decide the shortest path between his/her starting city and the destination. If such a shortest path is not unique, you are supposed to output the one with the minimum cost, which is guaranteed to be unique.

#include<iostream>
#include<vector>
#include<string.h>
using namespace std;

int N,M,S,D,dis[500][500],cost[500][500];
vector<int>v[500];
int mindis[500];
vector<int>path,final_ans;
int mindistoD=10000000,mincosttoD;

void dfs(int curcity,int curdis,int curcost){
    if(curdis>mindis[curcity])return;
    path.emplace_back(curcity);
    if(curcity==D){
        if(curdis<mindistoD||(curdis==mindistoD&&curcost<mincosttoD)){
            final_ans=path;
            mindistoD=mindis[D]=curdis;
            mincosttoD=curcost;
        }
    }
    else{
        if(curdis<mindis[curcity])mindis[curcity]=curdis;
        for(int each:v[curcity]){
            dfs(each,curdis+dis[curcity][each],curcost+cost[curcity][each]);
        }
    }
    path.pop_back();
}

int main(){
    int i,j,k,l;
    cin>>N>>M>>S>>D;
    while(M--){
        cin>>i>>j>>k>>l;
        v[i].emplace_back(j);
        v[j].emplace_back(i);
        dis[i][j]=dis[j][i]=k;
        cost[i][j]=cost[j][i]=l;
    }
    for(i=0;i<N;i++)mindis[i]=10000000;
    dfs(S,0,0);
    for(int each:final_ans)
        cout<<each<<" ";
    cout<<mindistoD<<" "<<mincosttoD;
}

在这里插入图片描述

如果采用memset来初始化数组会出现错误。

1031 Hello World for U (20 分)

Given any string of N (≥5) characters, you are asked to form the characters into the shape of U. For example, helloworld can be printed as:

h  d
e  l
l  r
lowo

That is, the characters must be printed in the original order, starting top-down from the left vertical line with n 1 ​ characters, then left to right along the bottom line with n 2 ​ characters, and finally bottom-up along the vertical line with n 3 ​ characters. And more, we would like U to be as squared as possible – that is, it must be satisfied that n 1 ​ =n 3 ​ =max { k | k≤n 2 ​ for all 3≤n 2 ​ ≤N } with n 1 ​ +n 2 ​ +n 3 ​ −2=N.

#include<iostream>
#include<cstring>
using namespace std;

int main(){
    string s;
    cin>>s;
    int i,j,k;
    int n1,n2,n3;
    n1=n2=(s.length()+2)/3;
    n2=s.length()-n1-n2+2;
    for(i=0;i<n1-1;i++){
        cout<<s[i];
        for(j=0;j<n2-2;j++){
            cout<<" ";
        }
        cout<<s[s.length()-i-1]<<endl;
    }
    cout<<s[n1-1];
    for(i=n1;i<=s.length()-n1;i++){
        cout<<s[i];
    }
}

1032 Sharing (25 分)

To store English words, one method is to use linked lists and store a word letter by letter. To save some space, we may let the words share the same sublist if they share the same suffix. For example, loading and being are stored as showed in Figure 1. 在这里插入图片描述
Figure 1
You are supposed to find the starting position of the common suffix (e.g. the position of i in Figure 1).

#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;

struct node{
    char data;
    int next;
};

node n[100000];

int main(){
    int h1,h2,N,i;
    cin>>h1>>h2>>N;
    while(N--)
        cin>>i>>n[i].data>>n[i].next;
    int j,k;
    vector<int>v1,v2;
    for(i=h1;i!=-1;i=n[i].next)
        v1.emplace_back(i);
    for(i=h2;i!=-1;i=n[i].next)
        v2.emplace_back(i);
    for(i=v1.size()-1,j=v2.size()-1;i>=0&&j>=0&&v1[i]==v2[j];i--,j--);
    if(i==v1.size()-1)printf("-1");
    else printf("%05d",v1[i+1]);
    return 0;
}

1033 To Fill or Not to Fill (25 分)

With highways available, driving a car from Hangzhou to any other city is easy. But since the tank capacity of a car is limited, we have to find gas stations on the way from time to time. Different gas station may give different price. You are asked to carefully design the cheapest route to go.

#include<algorithm>
#include<iostream>
#include<map>
using namespace std;

struct station{
    double pi,di;
};

double Cmax,D,Davg;
int N;
station s[501];

bool cmp(station x,station y){
    return x.di<y.di;
}

int main(){
    int i,j,k;
    cin>>Cmax>>D>>Davg>>N;
    for(i=0;i<N;i++)
        cin>>s[i].pi>>s[i].di;
    s[N].di=D;
    sort(s,s+N+1,cmp);
    
    double curdis=0,curcost=0;
    map<double,int>M;
    
    for(i=j=0;s[i].di<D;i++){
        if(curdis<s[i].di){
            if(!M.size())break;
            curcost+=M.begin()->first*(s[i].di-curdis)/Davg;
            curdis=s[i].di;
        }
        M[s[i].pi]++;
        
        while(j<=i&&s[j].di+Cmax*Davg<s[i+1].di){
            curcost+=M.begin()->first*(s[j].di+Cmax*Davg-curdis)/Davg;
            curdis=s[j].di+Cmax*Davg;
            M[s[j].pi]--;
            if(!M[s[j].pi])M.erase(s[j].pi);
            j++;
        }
    }
    if(!M.size()){
        printf("The maximum travel distance = %.2f",curdis);
    }
    else{
        curcost+=M.begin()->first*(D-curdis)/Davg;
        curdis=D;
        printf("%.2f",curcost);
    }
}

1034 Head of a Gang (30 分)

One way that the police finds the head of a gang is to check people’s phone calls. If there is a phone call between A and B, we say that A and B is related. The weight of a relation is defined to be the total time length of all the phone calls made between the two persons. A “Gang” is a cluster of more than 2 persons who are related to each other with total relation weight being greater than a given threshold K. In each gang, the one with maximum total weight is the head. Now given a list of phone calls, you are supposed to find the gangs and the heads.

#include<iostream>
#include<vector>
#include<unordered_map>
#include<algorithm>
using namespace std;

struct gang{
    vector<int>member;
    string head;
    int totaltime;
};

int N,K,minute[2001]={0},visited[2001]={0};
unordered_map<string,int>M1;
unordered_map<int,string>M2;
vector<int>v[2001];

gang g[2001];
int num_of_gang=0;

void dfs(int cur){
    if(visited[cur])return;
    visited[cur]=1;
    g[num_of_gang].member.emplace_back(cur);
    g[num_of_gang].totaltime+=minute[cur];
    for(int each:v[cur])
        dfs(each);
}

bool cmp(gang x,gang y){
    return x.head<y.head;
}

int main(){
    int i,j,k,l;
    cin>>N>>K;
    for(i=0;i<N;i++){
        string s1,s2;
        cin>>s1>>s2>>l;
        if(M1.count(s1))j=M1[s1];
        else{
            j=M1[s1]=M1.size()+1;
            M2[j]=s1;
        }
        if(M1.count(s2))k=M1[s2];
        else{
            k=M1[s2]=M1.size()+1;
            M2[k]=s2;
        }
        minute[j]+=l;
        minute[k]+=l;
        v[j].emplace_back(k);
        v[k].emplace_back(j);
    }
    
    for(i=0;i<=M1.size();i++){
        if(!visited[i]){
            g[num_of_gang].member.clear();
            g[num_of_gang].totaltime=0;
            dfs(i);
            if(g[num_of_gang].member.size()>2&&g[num_of_gang].totaltime>K*2){
                int maxminute=0;
                int head;
                for(int each:g[num_of_gang].member){
                    if(minute[each]>maxminute){
                        maxminute=minute[each];
                        head=each;
                    }
                }
                g[num_of_gang].head=M2[head];
                num_of_gang++;
            }
        }
    }
    sort(g,g+num_of_gang,cmp);
    cout<<num_of_gang<<endl;
    for(i=0;i<num_of_gang;i++){
        cout<<g[i].head<<' '<<g[i].member.size()<<endl;
    }
}

1035 Password (20 分)

To prepare for PAT, the judge sometimes has to generate random passwords for the users. The problem is that there are always some confusing passwords since it is hard to distinguish 1 (one) from l (L in lowercase), or 0 (zero) from O (o in uppercase). One solution is to replace 1 (one) by @, 0 (zero) by %, l by L, and O by o. Now it is your job to write a program to check the accounts generated by the judge, and to help the juge modify the confusing passwords.

#include<iostream>
using namespace std;

struct account{
    string s1,s2;
    int modified=0;
};

account a[1000];

int change(char &c){
    if(c=='0')c='%';
    else if(c=='1')c='@';
    else if(c=='O')c='o';
    else if(c=='l')c='L';
    else return 0;
    return 1;
}

int main(){
    int N,i,j,k;
    cin>>N;
    for(i=0;i<N;i++){
        cin>>a[i].s1>>a[i].s2;
    }
    int count=0;
    for(i=0;i<N;i++){
        for(char &c:a[i].s2){
            if(change(c))a[i].modified=1;
        }
        if(a[i].modified)count++;
    }
    if(count){
        cout<<count<<endl;
        for(i=0;i<N;i++){
            if(a[i].modified){
                cout<<a[i].s1<<" "<<a[i].s2<<endl;
            }
        }
    }
    else{
        if(N>1){
            cout<<"There are "<<N<<" accounts and no account is modified";
        }
        else{
            cout<<"There is 1 account and no account is modified";
        }
    }
}

1036 Boys vs Girls (25 分)

This time you are asked to tell the difference between the lowest grade of all the male students and the highest grade of all the female students.

#include<iostream>
using namespace std;

struct student{
    string name,gender,ID;
    int grade;
};

student s[1000];

int main(){
    int i,j,k,N,haveboy=0,havegirl=0;
    cin>>N;
    for(i=0;i<N;i++){
        cin>>s[i].name>>s[i].gender>>s[i].ID>>s[i].grade;
        if(s[i].gender=="M")haveboy=1;
        else havegirl=1;
    }
    
    int max_girl_grade=-1;
    int girl_index;
    
    if(havegirl){
        for(i=0;i<N;i++){
            if(s[i].gender=="F"&&s[i].grade>max_girl_grade){
                max_girl_grade=s[i].grade;
                girl_index=i;
            }
        }
        cout<<s[girl_index].name<<" "<<s[girl_index].ID<<endl;
    }
    else cout<<"Absent\n";
    int min_boy_grade=1000;
    int boy_index;
    if(haveboy){
        for(i=0;i<N;i++){
            if(s[i].gender=="M"&&s[i].grade<min_boy_grade){
                min_boy_grade=s[i].grade;
                boy_index=i;
            }
        }
        cout<<s[boy_index].name<<" "<<s[boy_index].ID<<endl;
    }
    else cout<<"Absent\n";
    
    if(haveboy&&havegirl)
        cout<<max_girl_grade-min_boy_grade;
    else cout<<"NA";
}

1037 Magic Coupon (25 分)

The magic shop in Mars is offering some magic coupons. Each coupon has an integer N printed on it, meaning that when you use this coupon with a product, you may get N times the value of that product back! What is more, the shop also offers some bonus product for free. However, if you apply a coupon with a positive N to this bonus product, you will have to pay the shop N times the value of the bonus product… but hey, magically, they have some coupons with negative N’s!
For example, given a set of coupons { 1 2 4 −1 }, and a set of product values { 7 6 −2 −3 } (in Mars dollars M$) where a negative value corresponds to a bonus product. You can apply coupon 3 (with N being 4) to product 1 (with value M$7) to get M$28 back; coupon 2 to product 2 to get M$12 back; and coupon 4 to product 4 to get M$3 back. On the other hand, if you apply coupon 3 to product 4, you will have to pay M$12 to the shop.
Each coupon and each product may be selected at most once. Your task is to get as much money back as possible.

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

int main(){
    int N1,N2,i,j,sum=0;
    int a[100000],b[100000];
    cin>>N1;
    for(i=0;i<N1;i++)cin>>a[i];
    cin>>N2;
    for(i=0;i<N2;i++)cin>>b[i];
    sort(a,a+N1);
    sort(b,b+N2);
    for(i=j=0;i<N1&&j<N2&&a[i]<0&&b[i]<0;i++,j++)
        sum+=a[i]*b[j];
    for(i=N1-1,j=N2-1;i>=0&&j>=0&&a[i]>0&&b[j]>0;i--,j--)
        sum+=a[i]*b[j];
    cout<<sum;
    return 0;
}

1038 Recover the Smallest Number (30 分)

Given a collection of number segments, you are supposed to recover the smallest number from them. For example, given { 32, 321, 3214, 0229, 87 }, we can recover many numbers such like 32-321-3214-0229-87 or 0229-32-87-321-3214 with respect to different orders of combinations of these segments, and the smallest number is 0229-321-3214-32-87.

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

bool cmp(string x,string y){
    return x+y<y+x;
}

int main(){
    int N,i,j,k;
    string s[10000];
    cin>>N;
    for(i=0;i<N;i++)cin>>s[i];
    sort(s,s+N,cmp);
    
    string ans="";
    for(i=0;i<N;i++)ans+=s[i];
    
    for(i=0;ans[i]=='0';i++);
    if(i==ans.size())cout<<0;
    while(i<ans.size()){
        cout<<ans[i];
        i++;
    }
}

1039 Course List for Student (25 分)

Zhejiang University has 40000 students and provides 2500 courses. Now given the student name lists of all the courses, you are supposed to output the registered course list for each student who comes for a query.

#include<iostream>
#include<unordered_map>
#include<set>
#include<cstdio>
using namespace std;

unordered_map<string,set<int>>M;

int main(){
    int N,K,i,j,k;
    cin>>N>>K;
    for(i=0;i<K;i++){
        scanf("%d %d",&j,&k);
        while(k--){
            char c[10];
            scanf("%s",c);
            string name;
            name=c;
            M[name].insert(j);
        }
    }
    while(N--){
        char c[10];
        string name;
        scanf("%s",c);
        name=c;
        cout<<name<<" "<<M[name].size();
        for(int each:M[name]){
            cout<<" "<<each;
        }
        cout<<endl;
    }
}

1040 Longest Symmetric String (25 分)

Given a string, you are supposed to output the length of the longest symmetric sub-string. For example, given Is PAT&TAP symmetric?, the longest symmetric sub-string is s PAT&TAP s, hence you must output 11.

#include<iostream>
using namespace std;

int main(){
    int i,j,k,ans=0;
    string s;
    getline(cin,s);
    for(i=0;i<s.size();i++){
        for(j=i,k=i;j>=0&&k<s.size()&&s[j]==s[k];j--,k++);
        if(k-j-1>ans)ans=k-j-1;
    }
    for(i=0;i+1<s.size();i++){
        for(j=i,k=i+1;j>=0&&k<s.size()&&s[j]==s[k];j--,k++);
        if(k-j-1>ans)ans=k-j-1;
     }
    cout<<ans;
}

1041 Be Unique (20 分)

Being unique is so important to people on Mars that even their lottery is designed in a unique way. The rule of winning is simple: one bets on a number chosen from [1,10 4 ]. The first one who bets on a unique number wins. For example, if there are 7 people betting on { 5 31 5 88 67 88 17 }, then the second one who bets on 31 wins.

#include<iostream>
using namespace std;

int main(){
    int marked[10001]={0};
    int N,a[100000],i,j;
    cin>>N;
    for(i=0;i<N;i++)
        cin>>a[i];
    for(i=0;i<N;i++){
        j=a[i];
        marked[j]++;
    }
    for(i=0;i<N;i++){
        j=a[i];
        if(marked[j]==1){
            cout<<j;
            return 0;
        }
    }
    cout<<"None";
    return 0;
}

1042 Shuffling Machine (20 分)

Shuffling is a procedure used to randomize a deck of playing cards. Because standard shuffling techniques are seen as weak, and in order to avoid “inside jobs” where employees collaborate with gamblers by performing inadequate shuffles, many casinos employ automatic shuffling machines. Your task is to simulate a shuffling machine.
The machine shuffles a deck of 54 cards according to a given random order and repeats for a given number of times. It is assumed that the initial status of a card deck is in the following order:

S1, S2, ..., S13, 
H1, H2, ..., H13,
C1, C2, ..., C13, 
D1, D2, ..., D13,  
J1, J2 

where “S” stands for “Spade”, “H” for “Heart”, “C” for “Club”, “D” for “Diamond”, and “J” for “Joker”. A given order is a permutation of distinct integers in [1, 54]. If the number at the i-th position is j, it means to move the card from position i to position j. For example, suppose we only have 5 cards: S3, H5, C1, D13 and J2. Given a shuffling order {4, 2, 5, 3, 1}, the result will be: J2, H5, D13, S3, C1. If we are to repeat the shuffling again, the result will be: C1, H5, S3, J2, D13.

#include<iostream>
using namespace std;

int main(){
    int i,j,k,l;
    string s[54];
    for(i=0;i<52;i++){
        j=i/13;
        if(j==0)s[i]+='S';
        else if(j==1)s[i]+='H';
        else if(j==2)s[i]+='C';
        else s[i]+='D';
        s[i]+=to_string(i%13+1);
    }
    s[52]="J1";
    s[53]="J2";
    
    int K,gowhere[54];
    cin>>K;
    for(i=0;i<54;i++)cin>>gowhere[i];
    while(K--){
        string temp[54];
        for(i=0;i<54;i++){
            temp[gowhere[i]-1]=s[i];
        }
        for(i=0;i<54;i++)s[i]=temp[i];
    }
    for(i=0;i<54;i++){
        if(i)cout<<" ";
        cout<<s[i];
    }
}

1043 Is It a Binary Search Tree (25 分)

A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:
The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than or equal to the node’s key. Both the left and right subtrees must also be binary search trees. If we swap the left and right subtrees of every node, then the resulting tree is called the Mirror Image of a BST.
Now given a sequence of integer keys, you are supposed to tell if it is the preorder traversal sequence of a BST or the mirror image of a BST.

#include<iostream>
#include<vector>
using namespace std;

struct node{
    int data;
    node*left,*right;
};

int N,a[1001],used;
vector<int>post;

node* makeBST(int cursor,int upp,int down){
    node *p=new node;
    used++;
    p->data=a[cursor];
    int i;
    for(i=cursor+1;i<N&&a[i]>=down&&a[i]<a[cursor];i++);
    if(i==cursor+1)p->left=NULL;
    else p->left=makeBST(cursor+1,a[cursor],down);
    if(i<N&&a[i]>=a[cursor]&&a[i]<upp)p->right=makeBST(i,upp,a[cursor]);
    else p->right=NULL;
    return p;
}

node* makeMBST(int cursor,int upp,int down){
    node *p=new node;
    used++;
    p->data=a[cursor];
    int i;
    for(i=cursor+1;i<N&&a[i]<upp&&a[i]>=a[cursor];i++);
    if(i==cursor+1)p->left=NULL;
    else p->left=makeMBST(cursor+1,upp,a[cursor]);
    if(i<N&&a[i]<a[cursor]&&a[i]>=down)p->right=makeMBST(i,a[cursor],down);
    else p->right=NULL;
    return p;
}

void posttravel(node *root){
    if(!root)return;
    posttravel(root->left);
    posttravel(root->right);
    post.emplace_back(root->data);
}

int main(){
    cin>>N;
    int i,j,k;
    for(i=0;i<N;i++)cin>>a[i];
    
    used=0;
    node *root=makeBST(0,1000000000,-1000000000);
    if(used==N){
        cout<<"YES\n";
        posttravel(root);
        for(i=0;i<post.size();i++){
            if(i)cout<<" ";
            cout<<post[i];
        }
    }
    else{
        used=0;
        root=makeMBST(0,1000000000,-1000000000);
        if(used==N){
            cout<<"YES\n";
            posttravel(root);
            for(i=0;i<post.size();i++){
                if(i)cout<<" ";
                cout<<post[i];
            }
        }
        else{
            cout<<"NO";
            return 0;
        }
    }
}

1044 Shopping in Mars (25 分)

Shopping in Mars is quite a different experience. The Mars people pay by chained diamonds. Each diamond has a value (in Mars dollars M$). When making the payment, the chain can be cut at any position for only once and some of the diamonds are taken off the chain one by one. Once a diamond is off the chain, it cannot be taken back. For example, if we have a chain of 8 diamonds with values M$3, 2, 1, 5, 4, 6, 8, 7, and we must pay M$15. We may have 3 options:

  1. Cut the chain between 4 and 6, and take off the diamonds from the position 1 to 5 (with values 3+2+1+5+4=15).
  2. Cut before 5 or after 6, and take off the diamonds from the position 4 to 6 (with values 5+4+6=15).
  3. Cut before 8, and take off the diamonds from the position 7 to 8 (with values 8+7=15).

Now given the chain of diamond values and the amount that a customer has to pay, you are supposed to list all the paying options for the customer.
If it is impossible to pay the exact amount, you must suggest solutions with minimum lost.

#include<iostream>
#include<vector>
using namespace std;

int main(){
    int N,M,a[100000];
    int i,j,sum=0;
    vector<int>left,right;
    
    cin>>N>>M;
    for(i=0;i<N;i++)cin>>a[i];
    
    int minbig=200000000;
    for(i=j=0,sum=0;j<N||sum>=M;){
        if(sum<M){
            sum+=a[j];
            j++;
        }
        else if(sum>M){
            if(sum<minbig)minbig=sum;
            sum-=a[i];
            i++;
        }
        else{
            left.emplace_back(i+1);
            right.emplace_back(j);
            sum-=a[i];
            i++;
        }
    }
    if(left.size()){
        for(i=0;i<left.size();i++){
            cout<<left[i]<<"-"<<right[i]<<endl;
        }
        return 0;
    }
    
    M=minbig;
    for(i=j=0,sum=0;j<N||sum>=M;){
        if(sum<M){
            sum+=a[j];
            j++;
        }
        else if(sum>M){
            if(sum<minbig)minbig=sum;
            sum-=a[i];
            i++;
        }
        else{
            left.emplace_back(i+1);
            right.emplace_back(j);
            sum-=a[i];
            i++;
        }
    }
    if(left.size()){
        for(i=0;i<left.size();i++){
            cout<<left[i]<<"-"<<right[i]<<endl;
        }
        return 0;
    }
}

1045 Favorite Color Stripe (30 分)

Eva is trying to make her own color stripe out of a given one. She would like to keep only her favorite colors in her favorite order by cutting off those unwanted pieces and sewing the remaining parts together to form her favorite color stripe.
It is said that a normal human eye can distinguish about less than 200 different colors, so Eva’s favorite colors are limited. However the original stripe could be very long, and Eva would like to have the remaining favorite stripe with the maximum length. So she needs your help to find her the best result.
Note that the solution might not be unique, but you only have to tell her the maximum length. For example, given a stripe of colors {2 2 4 1 5 5 6 3 1 1 5 6}. If Eva’s favorite colors are given in her favorite order as {2 3 1 5 6}, then she has 4 possible best solutions {2 2 1 1 1 5 6}, {2 2 1 5 5 5 6}, {2 2 1 5 5 6 6}, and {2 2 3 1 1 5 6}.

#include<iostream>
using namespace std;

int Rank[201]={0};

int main(){
    int i,j,k;
    int a[201],N,M,favorite[201];
    cin>>N>>M;
    for(i=1;i<=M;i++){
        cin>>favorite[i];
        Rank[favorite[i]]=i;
    }
    int L,old[10000];
    cin>>L;
    for(i=0;i<L;i++)cin>>old[i];
    
    int longest_endwith[201]={0};
    for(i=0;i<L;i++){
        if(!Rank[old[i]])continue;
        j=Rank[old[i]];
        int max=0;
        for(k=1;k<=j;k++){
            if(longest_endwith[k]>max)max=longest_endwith[k];
        }
        longest_endwith[j]=max+1;
    }
    int ans=0;
    for(i=1;i<=M;i++){
        if(ans<longest_endwith[i])ans=longest_endwith[i];
    }
    cout<<ans;
}

1046 Shortest Distance (20 分)

The task is really simple: given N exits on a highway which forms a simple cycle, you are supposed to tell the shortest distance between any pair of exits.

#include<iostream>
using namespace std;

int main(){
    int N,a[100001],i,j,k;
    cin>>N;
    for(i=1;i<=N;i++)scanf("%d",a+i);
    int sum[100001];
    sum[1]=0;
    for(i=2;i<=N;i++){
        sum[i]=sum[i-1]+a[i-1];
    }
    int circle=sum[N]+a[N];
    int M;
    cin>>M;
    while(M--){
        cin>>i>>j;
        if(i>j){
            int temp=i;i=j;j=temp;
        }
        int d1=sum[j]-sum[i];
        int d2=circle-d1;
        if(d1<d2)cout<<d1<<endl;
        else cout<<d2<<endl;
    }
}

1047 Student List for Course (25 分)

Zhejiang University has 40,000 students and provides 2,500 courses. Now given the registered course list of each student, you are supposed to output the student name lists of all the courses.

#include<iostream>
#include<vector>
#include<algorithm>
#include<string.h>
using namespace std;

struct student{
    char name[5];
    vector<int>course;
};

student s[40000];
vector<int>v[2501];

bool cmp(student &x,student &y){
    return strcmp(x.name,y.name)<0;
}

int main(){
    int N,K;
    int i,j,k,l;
    scanf("%d %d",&N,&K);
    getchar();
    for(i=0;i<N;i++){
        for(j=0;j<4;j++)
            s[i].name[j]=getchar();
        getchar();
        s[i].name[4]=0;
        scanf("%d",&j);
        while(j--){
            scanf("%d",&k);
            s[i].course.emplace_back(k);
        }
        getchar();
    }
    
    sort(s,s+N,cmp);
    
    for(i=0;i<N;i++){
        for(int each:s[i].course)
            v[each].emplace_back(i);
    }
    for(i=1;i<=K;i++){
        printf("%d %u\n",i,v[i].size());
        for(int each:v[i])
            printf("%s\n",s[each].name);
    }
}

1048 Find Coins (25 分)

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she could only use exactly two coins to pay the exact amount. Since she has as many as 10 5 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find two coins to pay for it.

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

int main(){
    int N,M;
    cin>>N>>M;
    int a[100000],i,j,k;
    for(i=0;i<N;i++)cin>>a[i];
    
    sort(a,a+N);
    
    for(i=0,j=N-1;i<j;){
        int sum=a[i]+a[j];
        if(sum==M){
            cout<<a[i]<<" "<<a[j];
            return 0;
        }
        if(sum<M)
            i++;
        else j--;
    }
    cout<<"No Solution";
}

1049 Counting Ones (30 分)

The task is simple: given any positive integer N, you are supposed to count the total number of 1’s in the decimal form of the integers from 1 to N. For example, given N being 12, there are five 1’s in 1, 10, 11, and 12.

#include<iostream>
using namespace std;

int a[]={1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000};
int b[]={0,1, 20, 300, 4000, 50000, 600000, 7000000, 80000000, 900000000};

int count(int n){
    if(!n)return 0;
    int i,j;
    for(i=0;n/a[i]>9;i++);
    j=n/a[i];
    if(j==1){
        return b[i]+1+count(n-a[i])+n-a[i];
    }
    else{
        return b[i]*j+a[i]+count(n-j*a[i]); 
    }
}

int main(){
    int N;
    cin>>N;
    cout<<count(N);
}

1050 String Subtraction (20 分)

Given two strings S1and S2 , S=S1 ​−S2 ​is defined to be the remaining string after taking all the characters in S2 ​from S1. Your task is simply to calculate S1−S2 for any given strings. However, it might not be that simple to do it fast.

#include<iostream>
using namespace std;

int main(){
    int show_in_s2[128]={0};
    string s1,s2;
    getline(cin,s1);
    getline(cin,s2);
    for(char c:s2)
        show_in_s2[c]=1;
    for(char c:s1){
        if(!show_in_s2[c])
            cout<<c;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南宫萧幕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值