PAT甲级1051~1075

1051 Pop Sequence (25 分)

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, …, N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack.
For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

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

int main(){
    int M,N,K;
    int i,j,k;
    cin>>M>>N>>K;
    while(K--){
        stack<int>s;
        int a[1000];
        for(i=0;i<N;i++)cin>>a[i];
        j=0;
        for(i=0;i<N;i++){
            if(a[i]>j)
                while(s.size()<M&&a[i]>j){
                    s.push(j+1);
                    j++;
                }
            if(a[i]>j)break;
            else if(s.top()!=a[i])break;
            else s.pop();
        }
        if(i==N)cout<<"YES\n";
        else cout<<"NO\n";
    }
}

1052 Linked List Sorting (25 分)

A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.

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

struct node{
    int key,next;
};

node n[100000];
vector<int>v;

bool cmp(int x,int y){
    return n[x].key<n[y].key;
}

int main(){
    int N,head,i,j,k;
    cin>>N>>head;
    while(N--){
        int address;
        cin>>address;
        cin>>n[address].key>>n[address].next;
    }
    for(i=head;i>=0;i=n[i].next){
        v.emplace_back(i);
    }
    sort(v.begin(),v.end(),cmp);
    cout<<v.size();
    for(i=0;i<v.size();i++)
        printf(" %05d\n%05d %d",v[i],v[i],n[v[i]].key);
    cout<<" "<<-1;
}

1053 Path of Equal Weight (30 分)

Given a non-empty tree with root R, and with weight W i ​ assigned to each tree node T i ​ . The weight of a path from R to L is defined to be the sum of the weights of all the nodes along the path from R to any leaf node L.
Now given any weighted tree, you are supposed to find all the paths with their weights equal to a given number. For example, let’s consider the tree showed in the following figure: for each node, the upper number is the node ID which is a two-digit number, and the lower number is the weight of that node. Suppose that the given number is 24, then there exists 4 different p请添加图片描述
aths which have the same given weight: {10 5 2 7}, {10 4 10}, {10 3 3 6 2} and {10 3 3 6 2}, which correspond to the red edges in the figure.

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

struct node{
    int ID,weight,num_of_children;
    vector<int>children;
};

int N,M,S;
node n[100];
vector<int>path;
vector<vector<int>>ans;

bool cmp(int x,int y){
    return n[x].weight>n[y].weight;
}

void dfs(int cur,int curweight){
    path.emplace_back(n[cur].weight);
    if(!n[cur].num_of_children){
        if(curweight==S){
            ans.emplace_back(path);
        }
    }
    else{
        for(int each:n[cur].children)
            dfs(each,curweight+n[each].weight);
    }
    path.pop_back();
}

int main(){
    int i,j,k;
    cin>>N>>M>>S;
    for(i=0;i<N;i++)cin>>n[i].weight;
    while(M--){
        cin>>i>>j;
        n[i].num_of_children=j;
        while(j--){
            cin>>k;
            n[i].children.emplace_back(k);
        }
    }
    for(i=0;i<N;i++){
        if(n[i].num_of_children){
            sort(n[i].children.begin(),n[i].children.end(),cmp);
        }
    }
    dfs(0,n[0].weight);
    
    for(i=0;i<ans.size();i++){
        for(j=0;j<ans[i].size();j++){
            if(j>0)cout<<" ";
            cout<<ans[i][j];
        }
        cout<<endl;
    }
}

1054 The Dominant Color (20 分)

Behind the scenes in the computer’s memory, color is always talked about as a series of 24 bits of information for each pixel. In an image, the color with the largest proportional area is called the dominant color. A strictly dominant color takes more than half of the total area. Now given an image of resolution M by N (for example, 800×600), you are supposed to point out the strictly dominant color.

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

unordered_map<int,int>MAP;

int main(){
    int N,M,total,i,j,k;
    scanf("%d %d",&N,&M);
    total=N*M;
    for(i=0;i<total;i++){
        scanf("%d",&j);
        MAP[j]++;
        if(MAP[j]>total/2){
            cout<<j;
            return 0;
        }
    }
}

1055 The World’s Richest (25 分)

Forbes magazine publishes every year its list of billionaires based on the annual ranking of the world’s wealthiest people. Now you are supposed to simulate this job, but concentrate only on the people in a certain range of ages. That is, given the net worths of N people, you must find the M richest people in a given range of their ages.

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

struct person{
    char name[10];
    int age;
    int money;
};

person p[100000];
int N,K;

bool cmp(person&x,person&y){
    if(x.money!=y.money)return x.money>y.money;
    if(x.age!=y.age)return x.age<y.age;
    return strcmp(x.name,y.name)<0;
}

int main(){
    int i,j,k;
    cin>>N>>K;
    for(i=0;i<N;i++){
        scanf("%s",p[i].name);
        scanf("%d %d",&p[i].age,&p[i].money);
    }
    sort(p,p+N,cmp);
    int M,Min,Max;
    for(i=1;i<=K;i++){
        scanf("%d %d %d",&M,&Min,&Max);
        printf("Case #%d:\n",i);
        k=0;
        for(j=0;j<N;j++){
            if(p[j].age<=Max&&p[j].age>=Min){
                printf("%s %d %d\n",p[j].name,p[j].age,p[j].money);
                k++;
                if(k==M)break;
            }
        }
        if(!k)cout<<"None\n";
    }
}

1056 Mice and Rice (25 分)

Mice and Rice is the name of a programming contest in which each programmer must write a piece of code to control the movements of a mouse in a given map. The goal of each mouse is to eat as much rice as possible in order to become a FatMouse.
First the playing order is randomly decided for N P ​ programmers. Then every N G ​ programmers are grouped in a match. The fattest mouse in a group wins and enters the next turn. All the losers in this turn are ranked the same. Every N G ​ winners are then grouped in the next match until a final winner is determined.
For the sake of simplicity, assume that the weight of each mouse is fixed once the programmer submits his/her code. Given the weights of all the mice and the initial playing order, you are supposed to output the ranks for the programmers.

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

int Np,Ng;
vector<int>players;

int main(){
    int i,j,k,l,score[1000],rank[1000];
    cin>>Np>>Ng;
    for(i=0;i<Np;i++)cin>>score[i];
    for(i=0;i<Np;i++){
        cin>>j;
        players.emplace_back(j);
    }
    for(int num=Np;num>1;){
        vector<int>nextturn;
        for(i=0;i<num;i+=Ng){
            int jinji=i;
            for(j=i+1;j<i+Ng&&j<num;j++){
                if(score[players[j]]>score[players[jinji]])
                    jinji=j;
            }
            nextturn.emplace_back(players[jinji]);
            for(j=i;j<i+Ng&&j<num;j++){
                if(j!=jinji){
                    rank[players[j]]=num/Ng+(num%Ng?1:0)+1;
                }
            }
        }
        players=nextturn;
        num=num/Ng+(num%Ng?1:0);
    }
    rank[players[0]]=1;
    for(i=0;i<Np;i++){
        if(i)cout<<" ";
        cout<<rank[i];
    }
}

1057 Stack (30 分)

Stack is one of the most fundamental data structures, which is based on the principle of Last In First Out (LIFO). The basic operations include Push (inserting an element onto the top position) and Pop (deleting the top element). Now you are supposed to implement a stack with an extra operation: PeekMedian – return the median value of all the elements in the stack. With N elements, the median value is defined to be the (N/2)-th smallest element if N is even, or ((N+1)/2)-th if N is odd.

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

map<int,int>M;
map<int,int>::iterator mid;
int beforemid;
stack<int>S;

void adjust_mid(){
    if(beforemid>=(S.size()+1)/2){
        mid--;
        beforemid-=mid->second;
    }
    else if(beforemid+mid->second<(S.size()+1)/2){
        beforemid+=mid->second;
        mid++;
    }
}

int main(){
    int N;
    cin>>N;
    while(N--){
        string command;
        cin>>command;
        if(command[1]=='u'){
            int key;
            cin>>key;
            S.push(key);
            M[key]++;
            if(S.size()==1){
                mid=M.begin();
                beforemid=0;
            }
            else{
                if(key<mid->first)beforemid++;
                adjust_mid();
            }
        }
        else if(command[1]=='o'){
            if(!S.size())cout<<"Invalid\n";
            else{
                int key;
                key=S.top();
                cout<<key<<endl;
                S.pop();
                M[key]--;
                if(key<mid->first)beforemid--;
                adjust_mid();
                if(M[key]==0){
                    if(mid->first==key)mid++;
                    M.erase(key);
                }
            }
        }
        else{
            if(!S.size())cout<<"Invalid\n";
            else
                cout<<mid->first<<endl;
        }
    }
}

1058 A+B in Hogwarts (20 分)

If you are a fan of Harry Potter, you would know the world of magic has its own currency system – as Hagrid explained it to Harry, “Seventeen silver Sickles to a Galleon and twenty-nine Knuts to a Sickle, it’s easy enough.” Your job is to write a program to compute A+B where A and B are given in the standard form of Galleon.Sickle.Knut (Galleon is an integer in [0,10 7 ], Sickle is an integer in [0, 17), and Knut is an integer in [0, 29)).

#include<iostream>
using namespace std;

int main(){
    long long a,b,c;
    long long x1,x2,x3;
    char d;
    cin>>a>>d>>b>>d>>c;
    x1=a*17*29+b*29+c;
    cin>>a>>d>>b>>d>>c;
    x2=a*17*29+b*29+c;
    x3=x1+x2;
    c=x3%29;
    b=x3/29%17;
    a=x3/17/29;
    cout<<a<<'.'<<b<<'.'<<c;
}

1059 Prime Factors (25 分)

Given any positive integer N, you are supposed to find all of its prime factors, and write them in the format N = p1k1 ​×p2k2​×⋯×pmkm​.

#include<iostream>
using namespace std;

int main(){
    int N,i,j,k;
    cin>>N;
    if(N==1){
        cout<<"1=1";
        return 0;
    }
    cout<<N<<"=";
    int start=0;
    for(i=2;i*i<=N;i++){
        j=0;
        while(N%i==0){
            j++;
            N/=i;
        }
        if(j){
            if(start)cout<<"*";
            else start=1;
            cout<<i;
            if(j>1)cout<<"^"<<j;
        }
    }
    if(N>1){
        if(start)cout<<"*";
        else start=1;
        cout<<N;
    }
}

1060 Are They Equal (25 分)

If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered equal since they are both saved as 0.123×105 with simple chopping. Now given the number of significant digits on a machine and two float numbers, you are supposed to tell if they are treated equal in that machine.

#include<iostream>
using namespace std;

int a_[300]={0},b_[300]={0};
int *a=a_+150,*b=b_+150;
int N;

void putsto(string s,int *digit){
    int i,j,k;
    for(i=0;i<s.size();i++)
        if(s[i]=='.')
            break;
    if(i==s.size())
        for(j=0;j<s.size();j++)
            digit[s.size()-1-j]=s[j]-'0';
    else{
        for(j=0;j<i;j++)
            digit[i-1-j]=s[j]-'0';
        for(j=i+1;j<s.size();j++)
            digit[i-j]=s[j]-'0';
    }
}

bool checksame(){
    int i,j,k;
    for(i=120;i>-120;i--){
        if(a[i]||b[i]){
            if(a[i]&&b[i])
                break;
            else 
                return false;
        }
    }
    if(i==-120)
        return true;
    for(j=0;j<N;j++)
        if(a[i-j]!=b[i-j])
            break;
    if(j==N)
        return true;
    else  
        return false;
}

void print(int *digit){
    int i,j,k;
    for(i=120;i>-120;i--)
        if(digit[i]!=0)
            break;
    if(i==-120){
        cout<<" "<<"0.";
        for(j=0;j<N;j++)
            cout<<0;
        cout<<"*10^0";
    }
    else{
        cout<<" "<<"0.";
        for(j=0;j<N;j++)
            cout<<digit[i-j];
        cout<<"*10^"<<i+1;
    }
}

int main(){
    string s1,s2;
    cin>>N>>s1>>s2;
    
    putsto(s1,a);
    putsto(s2,b);
    
    bool signal=checksame();
    if(signal==true)
        cout<<"YES";
    else 
        cout<<"NO";
    
    print(a);
    if(signal==false)
        print(b);
}

1061 Dating (20 分)

Sherlock Holmes received a note with some strange strings: Let’s date! 3485djDkxh4hhGE 2984akDfkkkkggEdsb s&hgsfdk d&Hyscvnm. It took him only a minute to figure out that those strange strings are actually referring to the coded time Thursday 14:04 – since the first common capital English letter (case sensitive) shared by the first two strings is the 4th capital letter D, representing the 4th day in a week; the second common character is the 5th capital letter E, representing the 14th hour (hence the hours from 0 to 23 in a day are represented by the numbers from 0 to 9 and the capital letters from A to N, respectively); and the English letter shared by the last two strings is s at the 4th position, representing the 4th minute. Now given two pairs of strings, you are supposed to help Sherlock decode the dating time.

#include<iostream>
using namespace std;

string weekday[7]={"MON","TUE","WED","THU","FRI","SAT","SUN"};

int main(){
    string s1,s2,s3,s4;
    cin>>s1>>s2>>s3>>s4;
    int i,j,k;
    int day;
    for(i=0;;i++)
        if(s1[i]>='A'&&s1[i]<='G'&&s1[i]==s2[i])
            break;
    day=s1[i]-'A';
    int hour;
    for(j=i+1;;j++){
        if((isdigit(s1[j])||(s1[j]>='A'&&s1[j]<='N'))&&s1[j]==s2[j])break;
    }
    if(isdigit(s1[j]))hour=s1[j]-'0';
    else hour=s1[j]-'A'+10;
    int minute;
    for(i=0;;i++){
        if(isalpha(s3[i])&&s3[i]==s4[i])break;
    }
    minute=i;
    cout<<weekday[day];
    printf(" %02d:%02d",hour,minute);
}

1062 Talent and Virtue (25 分)

About 900 years ago, a Chinese philosopher Sima Guang wrote a history book in which he talked about people’s talent and virtue. According to his theory, a man being outstanding in both talent and virtue must be a “sage(圣人)”; being less excellent but with one’s virtue outweighs talent can be called a “nobleman(君子)”; being good in neither is a “fool man(愚人)”; yet a fool man is better than a “small man(小人)” who prefers talent than virtue.
Now given the grades of talent and virtue of a group of people, you are supposed to rank them according to Sima Guang’s theory.

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

struct person{
    int ID;
    int de,cai,total;
    int level;
};

person p[100000];

bool cmp(person x,person y){
    if(x.level!=y.level)return x.level<y.level;
    if(x.total!=y.total)return x.total>y.total;
    if(x.de!=y.de)return x.de>y.de;
    return x.ID<y.ID;
}

int main(){
    int N,L,H,i,j,k,l;
    int M=0;
    cin>>N>>L>>H;
    for(i=0;i<N;i++){
        scanf("%d %d %d",&j,&k,&l);
        p[i].ID=j;
        p[i].de=k;
        p[i].cai=l;
        p[i].total=k+l;
        if(k<L||l<L)p[i].level=5;
        else if(k>=H&&l>=H)p[i].level=1;
        else if(k>=H&&l<H)p[i].level=2;
        else if(k<H&&l<H&&k>=l)p[i].level=3;
        else p[i].level=4;
        if(p[i].level<=4)M++;
    }
    sort(p,p+N,cmp);
    cout<<M<<endl;
    for(i=0;i<M;i++){
        cout<<p[i].ID<<" "<<p[i].de<<" "<<p[i].cai<<endl;
    }
}

1063 Set Similarity (25 分)

Given two sets of integers, the similarity of the sets is defined to be Nc ​/Nt ​×100%, where Nc ​is the number of distinct common numbers shared by the two sets, and Ntis the total number of distinct numbers in the two sets. Your job is to calculate the similarity of any given pair of sets.

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

set<int>S[51];
set<int>::iterator it1,it2;

int main(){
    int N,i,j,k;
    cin>>N;
    for(i=1;i<=N;i++){
        scanf("%d",&j);
        while(j--){
            scanf("%d",&k);
            S[i].insert(k);
        }
    }
    int K;
    cin>>K;
    while(K--){
        scanf("%d %d",&i,&j);
        int Nc=0;
        for(it1=S[i].begin(),it2=S[j].begin();it1!=S[i].end()&&it2!=S[j].end();){
            if(*it1<*it2)
                it1++;
            else if(*it1>*it2)
                it2++;
            else{
                Nc++;
                it1++;
                it2++;
            }
        }
        int Nt=S[i].size()+S[j].size()-Nc;
        printf("%.1f%c\n",100.0*Nc/Nt,'%');
    }
}

1064 Complete Binary Search Tree (30 分)

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. A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.
Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

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

int N;
int a[1001];
vector<int>inorder;
vector<int>date;

void inordertraverse(int i){
    if(i>N)return;
    inordertraverse(i*2);
    inorder.emplace_back(i);
    inordertraverse(i*2+1);
}

int main(){
    int i,j,k;
    cin>>N;
    inordertraverse(1);
    for(i=0;i<N;i++){
        cin>>j;
        date.emplace_back(j);
    }
    sort(date.begin(),date.end());
    for(i=0;i<N;i++)
        a[inorder[i]]=date[i];
    queue<int>Q;
    Q.push(1);
    while(Q.size()){
        i=Q.front();
        Q.pop();
        if(i>1)cout<<" ";
        cout<<a[i];
        if(i*2<=N)
            Q.push(i*2);
        if(i*2+1<=N)
            Q.push(i*2+1);
    }
}

1065 A+B and C (64bit) (20 分)

Given three integers A, B and C in (−2 63 ,2 63 ), you are supposed to tell whether A+B>C.

#include<iostream>
using namespace std;

int A[50],B[50],C[50];

void input(int digit[],int k){
    int i,j=1;
    string s;
    cin>>s;
    if(s[0]=='-'){
        s=s.substr(1,s.size()-1);
        j=-1;
    }
    for(i=0;i<50;i++)
        digit[i]=0;
    for(i=0;i<s.size();i++){
        digit[s.size()-1-i]=s[i]-'0';
        digit[s.size()-1-i]*=j;
    }
    digit[25]=k;
    if(j==-1){
        for(i=0;i<=25;i++){
            if(digit[i]<0){
                digit[i+1]--;
                digit[i]+=10;
            }
        }
    }
}

void add(){
    int i,j,k;
    for(i=0;i<=25;i++)
        A[i]+=B[i];
    for(i=0;i<=25;i++){
        if(A[i]>=10){
            A[i]-=10;
            A[i+1]++;
        }
    }
}

bool judge(){
    int i;
    for(i=25;i>=0;i--){
        if(A[i]!=C[i]){
            if(A[i]>C[i])return true;
            else return false;
        }
    }
    return false;
}

int main(){
    int i,j,k,T;
    cin>>T;
    for(i=1;i<=T;i++){
        input(A,1);
        input(B,1);
        input(C,2);
  
        add();
        bool signal;
        signal=judge();
        if(signal==true)
            printf("Case #%d: true\n",i);
        else 
            printf("Case #%d: false\n",i);
    }
}

1066 Root of AVL Tree (25 分)

An AVL tree is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. Figures 1-4 illustrate the rotation rules.
请添加图片描述请添加图片描述
请添加图片描述
请添加图片描述
Now given a sequence of insertions, you are supposed to tell the root of the resulting AVL tree.

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

struct node{
    int data,lheight,rheight;
    node *lchild,*rchild;
};

void insert(node*&root,int i){
    if(root==NULL){
        root=new node;
        root->data=i;
        root->lchild=root->rchild=NULL;
        root->lheight=root->rheight=0;
    }
    else{
        if(i>root->data){
            insert(root->rchild,i);
            root->rheight=max(root->rchild->lheight,root->rchild->rheight)+1;
        }
        else{
            insert(root->lchild,i);
            root->lheight=max(root->lchild->lheight,root->lchild->rheight)+1;
        }
        if(root->lheight-root->rheight==2){
            if(root->lchild->lheight>root->lchild->rheight){//left left
                node*a=root;
                node*b=root->lchild;
                root=b;
                a->lchild=b->rchild;
                a->lheight=b->rheight;
                b->rchild=a;
                b->rheight++;
            }
            else{//left right
                node *a=root;
                node *b=root->lchild;
                node *c=root->lchild->rchild;
                root=c;
                b->rchild=c->lchild;
                b->rheight=c->lheight;
                a->lchild=c->rchild;
                a->lheight=c->rheight;
                c->lchild=b;
                c->rchild=a;
                c->lheight=b->lheight+1;
                c->rheight=b->rheight+1;
            }
        }
        else if(root->rheight-root->lheight==2){
            if(root->rchild->rheight>root->rchild->lheight){//right right
                node*a=root;
                node*b=root->rchild;
                root=b;
                a->rchild=b->lchild;
                a->rheight=b->lheight;
                b->lchild=a;
                b->lheight++;
            }
            else{//right left
                node *a=root;
                node *b=root->rchild;
                node *c=root->rchild->lchild;
                root=c;
                a->rchild=c->lchild;
                a->rheight=c->lheight;
                b->lchild=c->rchild;
                b->lheight=c->rheight;
                c->lchild=a;
                c->rchild=b;
                c->lheight=a->lheight+1;
                c->rheight=b->rheight+1;
            }
        }
    }
}

int main(){
    int N,i;
    node *Tree=NULL;
    cin>>N;
    while(N--){
        cin>>i;
        insert(Tree,i);
    }
    cout<<Tree->data;
}

1067 Sort with Swap(0, i) (25 分)

Given any permutation of the numbers {0, 1, 2,…, N−1}, it is easy to sort them in increasing order. But what if Swap(0, *) is the ONLY operation that is allowed to use? For example, to sort {4, 0, 2, 1, 3} we may apply the swap operations in the following way:

Swap(0, 1) => {4, 1, 2, 0, 3}
Swap(0, 3) => {4, 1, 2, 3, 0}
Swap(0, 4) => {0, 1, 2, 3, 4}

Now you are asked to find the minimum number of swaps need to sort the given permutation of the first N nonnegative integers.

#include<iostream>
using namespace std;

int N,a[100000],visited[100000]={0};
int cycle_length;

void dfs(int i){
    if(visited[i])return;
    visited[i]=1;
    cycle_length++;
    dfs(a[i]);
}

int main(){
    cin>>N;
    for(int i=0;i<N;i++)cin>>a[i];
    int total=0;
    for(int i=0;i<N;i++){
        if(!visited[i]){
            if(i!=a[i]){
                cycle_length=0;
                dfs(i);
                if(i==0)total+=cycle_length-1;
                else total+=cycle_length+1;
            }
        }
    }
    cout<<total;
}

1068 Find More Coins (30 分)

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 must pay the exact amount. Since she has as many as 104 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 some coins to pay for it.

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

int N,M,coin[10000];
vector<int>path;

bool dfs(int cur,int curmoney){
    path.emplace_back(coin[cur]);
    if(curmoney==M){
        return true;
    }
    else{
        for(int i=cur+1;i<N&&curmoney+coin[i]<=M;){
            if(dfs(i,curmoney+coin[i])==true)
                return true;
            else{
                int j;
                for(j=i+1;j<M&&coin[j]==coin[i];j++);
                i=j;
            }
        }
    }
    path.pop_back();
    return false;
}

int main(){
    int i,j,k;
    cin>>N>>M;
    for(i=0;i<N;i++)cin>>coin[i];
    sort(coin,coin+N);
    
    for(i=0;i<N&&coin[i]<=M;){
        if(dfs(i,coin[i])==true){
            for(i=0;i<path.size();i++){
                if(i)cout<<" ";
                cout<<path[i];
            }
            return 0;
        }
        else{
            //i++;
			for(j=i+1;j<M&&coin[j]==coin[i];j++);
            i=j;
        }
    }
    cout<<"No Solution";
}

1069 The Black Hole of Numbers (20 分)

For any 4-digit integer except the ones with all the digits being the same, if we sort the digits in non-increasing order first, and then in non-decreasing order, a new number can be obtained by taking the second number from the first one. Repeat in this manner we will soon end up at the number 6174 – the black hole of 4-digit numbers. This number is named Kaprekar Constant.
For example, start from 6767, we’ll get:

7766 - 6677 = 1089
9810 - 0189 = 9621
9621 - 1269 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
... ...

Given any 4-digit number, you are supposed to illustrate the way it gets into the black hole.

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

int main(){
    int N,a[4];
    cin>>N;
    do{
        a[0]=N%10;
        a[1]=N/10%10;
        a[2]=N/100%10;
        a[3]=N/1000;
        int big,small;
        sort(a,a+4);
        big=a[3]*1000+a[2]*100+a[1]*10+a[0];
        small=a[0]*1000+a[1]*100+a[2]*10+a[3];
        printf("%04d - %04d = %04d\n",big,small,big-small);
        N=big-small;
    }while(N&&N!=6174);
}

1070 Mooncake (25 分)

Mooncake is a Chinese bakery product traditionally eaten during the Mid-Autumn Festival. Many types of fillings and crusts can be found in traditional mooncakes according to the region’s culture. Now given the inventory amounts and the prices of all kinds of the mooncakes, together with the maximum total demand of the market, you are supposed to tell the maximum profit that can be made.
Note: partial inventory storage can be taken. The sample shows the following situation: given three kinds of mooncakes with inventory amounts being 180, 150, and 100 thousand tons, and the prices being 7.5, 7.2, and 4.5 billion yuans. If the market demand can be at most 200 thousand tons, the best we can do is to sell 150 thousand tons of the second kind of mooncake, and 50 thousand tons of the third kind. Hence the total profit is 7.2 + 4.5/2 = 9.45 (billion yuans).

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

struct mooncake{
    double amount,price,signal;
};

mooncake M[1000];

bool cmp(mooncake x,mooncake y){
    return x.signal>y.signal;
}

int main(){
    int N;
    double D;
    cin>>N>>D;
    int i;
    for(i=0;i<N;i++)
        cin>>M[i].amount;
    for(i=0;i<N;i++){
        cin>>M[i].price;
        M[i].signal=M[i].price/M[i].amount;
    }
    sort(M,M+N,cmp);
    double profit=0;
    for(i=0;i<N;i++){
        if(D>=M[i].amount){
            D-=M[i].amount;
            profit+=M[i].price;
        }
        else{
            profit+=M[i].signal*D;
            D=0;
            break;
        }
    }
    printf("%.2f",profit);
}

1071 Speech Patterns (25 分)

People often have a preference among synonyms of the same word. For example, some may prefer “the police”, while others may prefer “the cops”. Analyzing such patterns can help to narrow down a speaker’s identity, which is useful when validating, for example, whether it’s still the same person behind an online avatar.
Now given a paragraph of text sampled from someone’s speech, can you find the person’s most commonly used word?

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

unordered_map<string,int>M;

int preferword_times=0;
string preferword;

int main(){
    string s;
    getline(cin,s);
    int i,j,k,isalphanum[128]={0};
    for(i='0';i<='9';i++)isalphanum[i]=1;
    for(i='a';i<='z';i++)isalphanum[i]=1;
    for(i='A';i<='Z';i++)isalphanum[i]=1;
    
    for(char&c:s)
        c=tolower(c);
    
    for(i=0;i<s.size();){
        while(i<s.size()&&isalphanum[s[i]]==0)i++;
        if(i==s.size())break;
        for(j=i+1;j<s.size()&&isalphanum[s[j]]==1;j++);
        string temp=s.substr(i,j-i);
        k=++M[temp];
        if(k>preferword_times||(k==preferword_times&&temp<preferword)){
            preferword_times=k;
            preferword=temp;
        }
        i=j;
    }
    cout<<preferword<<" "<<preferword_times;
}

1072 Gas Station (30 分)

A gas station has to be built at such a location that the minimum distance between the station and any of the residential housing is as far away as possible. However it must guarantee that all the houses are in its service range.
Now given the map of the city and several candidate locations for the gas station, you are supposed to give the best recommendation. If there are more than one solution, output the one with the smallest average distance to all the houses. If such a solution is still not unique, output the one with the smallest index number.

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

int N,M,K,Ds;//N居民数,M侯选站数,K路数,Ds服务范围
int dis[1012][1012];
vector<int>v[1012];
int mindis[1012];
int mindistohouse[1012],atservice[1012],totaldis[1012];

void dfs(int cur,int curdis){
    mindis[cur]=curdis;
    for(int each:v[cur]){
        int temp=curdis+dis[cur][each];
        if(temp<mindis[each])
            dfs(each,temp);
    }
}

bool cmp(int x,int y){
    if(atservice[x]!=atservice[y])return atservice[x]>atservice[y];
    if(mindistohouse[x]!=mindistohouse[y])return mindistohouse[x]>mindistohouse[y];
    if(totaldis[x]!=totaldis[y])return totaldis[x]<totaldis[y];
    return x<y;
}

void read(int&p){
    char c;
    c=getchar();
    if(c=='G'){
        p=0;
        while(isdigit(c=getchar())){
            p=p*10+c-'0';
        }
        p+=N;
    }
    else{
        p=c-'0';
        while(isdigit(c=getchar())){
            p=p*10+c-'0';
        }
    }
}

int main(){
    int i,j,k,l;
    cin>>N>>M>>K>>Ds;
    getchar();
    while(K--){
        read(j);
        read(k);
        read(l);
        v[k].emplace_back(j);
        v[j].emplace_back(k);
        dis[k][j]=dis[j][k]=l;
    }//输入
    for(i=N+1;i<=N+M;i++){
        for(j=1;j<=N+M;j++)mindis[j]=1000000000;
        dfs(i,0);
        //最短距离尽量远/都在服务范围内/平均距离尽量进/下标小
        mindistohouse[i]=1000000000;
        atservice[i]=1;
        totaldis[i]=0;
        for(j=1;j<=N;j++){
            if(mindis[j]<mindistohouse[i])mindistohouse[i]=mindis[j];
            if(mindis[j]>Ds){
                atservice[i]=0;
                break;
            }
            totaldis[i]+=mindis[j];
        }
    }
    int ans=N+1;
    for(i=N+2;i<=N+M;i++){
        if(cmp(i,ans)==true)ans=i;
    }
    if(!atservice[ans]){
        cout<<"No Solution";
    }
    else{
        cout<<"G"<<ans-N<<endl;
        printf("%.1f %.1f",double(mindistohouse[ans]),double(totaldis[ans])/double(N));
    }
}

1073 Scientific Notation (20 分)

Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [±][1-9].[0-9]+E[±][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent’s signs are always provided even when they are positive.
Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.

#include<iostream>
using namespace std;

int main(){
    int _digit_[40000]={0};
    int *digit=_digit_+25000;
    string s;
    cin>>s;
    //0+-   1 int   2 . ......,epos "E"  +- ^
    int epos,i,j,k,l;
    for(epos=4;s[epos]!='E';epos++);
    
    int cishu=0,signal;
    if(s[epos+1]=='+')signal=1;
    else signal=-1;
    
    for(i=epos+2;i<s.size();i++)cishu=cishu*10+s[i]-'0';
    cishu*=signal;
    
    digit[cishu]=s[1]-'0';
    for(i=cishu-1;i>=cishu-(epos-3);i--){
        digit[i]=s[cishu+2-i]-'0';
    }
    int end=cishu-(epos-3);
    
    if(s[0]=='-')cout<<"-";
    if(cishu<0){
        cout<<"0.";
        for(i=-cishu-1;i--;)cout<<0;
        for(i=cishu;i>=end;i--)cout<<digit[i];
    }
    else{
        for(i=cishu;i>=0;i--)cout<<digit[i];
        if(end<0){
            cout<<".";
            for(i=-1;i>=end;i--)cout<<digit[i];
        }
    }
}

1074 Reversing Linked List (25 分)

Given a constant K and a singly linked list L, you are supposed to reverse the links of every K elements on L. For example, given L being 1→2→3→4→5→6, if K=3, then you must output 3→2→1→6→5→4; if K=4, you must output 4→3→2→1→5→6.

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

struct node{
    int data,next;
};

int head,N,K;
node n[100000];
vector<int>v;

int main(){
    int i,j,k,l;
    cin>>head>>N>>K;
    for(i=0;i<N;i++){
        cin>>j>>k>>l;
        n[j].data=k;
        n[j].next=l;
    }
    for(i=head;i>=0;i=n[i].next){
        v.emplace_back(i);
    }
    for(i=0;i+K<=v.size();i+=K){
        for(j=0;j<K/2;j++){
            int temp=v[i+j];
            v[i+j]=v[i+K-1-j];
            v[i+K-1-j]=temp;
        }
    }
    printf("%05d %d ",v[0],n[v[0]].data);
    for(i=1;i<v.size();i++){
        printf("%05d\n%05d %d ",v[i],v[i],n[v[i]].data);
    }
    printf("-1");
}

1075 PAT Judge (25 分)

The ranklist of PAT is generated from the status list, which shows the scores of the submissions. This time you are supposed to generate the ranklist for PAT.

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

struct student{
    int id;
    int score[6]={0,-2,-2,-2,-2,-2};
    int num_of_perfer=0;
    int show=0;
    int rnk;
};

int N,M,K;
int total[6];
student s[100000];

bool cmp(student x,student y){
    if(x.score[0]!=y.score[0])return x.score[0]>y.score[0];
    if(x.num_of_perfer!=y.num_of_perfer)return x.num_of_perfer>y.num_of_perfer;
    if(x.show!=y.show)return x.show>y.show;
    return x.id<y.id;
}

int main(){
    int i,j,k,l;
    cin>>N>>K>>M;
    for(i=1;i<=K;i++)cin>>total[i];
    while(M--){
        cin>>i>>j>>k;
        if(k>=0)s[i].show=1;
        if(k>s[i].score[j])s[i].score[j]=k;
    }
    for(i=1;i<=N;i++){
        s[i].id=i;
        for(j=1;j<=K;j++){
            if(s[i].score[j]>=0)s[i].score[0]+=s[i].score[j];
            if(s[i].score[j]==total[j])s[i].num_of_perfer++;
        }
    }
    sort(s+1,s+N+1,cmp);
    for(i=1;i<=N;i++){
        if(i==1||s[i].score[0]!=s[i-1].score[0]){
            s[i].rnk=i;
        }
        else{
            s[i].rnk=s[i-1].rnk;
        }
    }
    for(i=1;i<=N;i++){
        if(s[i].show==0)break;
        printf("%d %05d %d",s[i].rnk,s[i].id,s[i].score[0]);
        for(j=1;j<=K;j++){
            if(s[i].score[j]==-2)cout<<" -";
            else if(s[i].score[j]==-1)cout<<" 0";
            else cout<<" "<<s[i].score[j];
        }
        cout<<endl;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

南宫萧幕

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

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

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

打赏作者

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

抵扣说明:

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

余额充值