南開高階語言程式設計2--OJ題目答案

AuroraKelsey發表於2024-11-13

下面是南開高階語言程式設計2-2的oj題目答案,本人親測AC,供大家參考。
這裡還有一些上機考試tips
看這篇 https://www.cnblogs.com/AuroraKelsey/p/18542930

注意:素數是從2開始,2也是素數

第七章(運算子過載)

#include <cstdio>
#include <iostream>

using namespace std;
int gcd(int a, int b) {
    return b ? gcd(b, a % b) : a;
}
int lcm(int a, int b) {
    return a * b / gcd(a, b);
}
class Rational {
private:
    int fz, fm;

public:
    Rational() {
        fz = 0, fm = 1;
    }
    Rational(int z, int m) {
        if (!z) {
            fz = 0, m = 1;
        } else {
            int tmp = gcd(z, m);
            fz = z / tmp;
            fm = m / tmp;
        }
    }

    Rational operator+(Rational &x) {
        //分母通分
        int tmp = lcm(this->fm, x.fm);
        Rational res = Rational(tmp / this->fm * this->fz + tmp / x.fm * x.fz, tmp);
        return res;
    }
    Rational operator-(Rational &x) {
        //分母通分
        int tmp = lcm(this->fm, x.fm);
        Rational res = Rational(tmp / this->fm * this->fz - tmp / x.fm * x.fz, tmp);
        return res;
    }
    friend Rational operator*(Rational &x, Rational &y);
    friend Rational operator/(Rational &x, Rational &y);
    friend ostream &operator<<(ostream &out, Rational &x);

    Rational operator++() {
        this->fz += this->fm;
        if (!this->fz) {
            this->fm = 1;
        } else {
            int tmp = gcd(this->fz, this->fm);
            this->fz /= tmp;
            this->fm /= tmp;
        }
        return *this;//返回引用
    }
    Rational operator++(int) {//後置
        Rational res = Rational(this->fz + this->fm, this->fm);
        return res;//返回值
    }
    Rational operator=(const Rational &x) {
        Rational y = Rational(x.fz, x.fm);
        this->fz = y.fz;
        this->fm = y.fm;
        return *this;
    }
};
//友元沒有this指標
Rational operator*(Rational &x, Rational &y) {
    Rational res = Rational(x.fz * y.fz, x.fm * y.fm);
    return res;
}
Rational operator/(Rational &x, Rational &y) {
    Rational res = Rational(x.fz * y.fm, x.fm * y.fz);
    return res;
}
//ostream物件只能有一個,所以用引用,ostream是cout的資料型別
//只能用全域性函式過載
ostream &operator<<(ostream &out, Rational &x) {
    if (x.fm == 1) {
        out << x.fz;
    } else {
        if (x.fm < 0) {
            x.fm *= -1;
            x.fz *= -1;
        }
        out << x.fz << "/" << x.fm;
    }
    return out;
}
int main() {

    Rational R1, R2;
    int fenzi, fenmu;
    cin >> fenzi >> fenmu;
    Rational x = Rational(fenzi, fenmu);
    cin >> fenzi >> fenmu;
    Rational y = Rational(fenzi, fenmu);
    Rational res = x + y;
    cout << res << endl;
    res = x - y;
    cout << res << endl;
    res = x * y;
    cout << res << endl;
    res = x / y;
    cout << res << endl;
    res = x++;
    cout << res << " ";
    res = y++;
    cout << res << endl;
    res = Rational(1, 1);
    R1 = res / x;
    R2 = res / y;
    cout << R1 << " " << R2;
    return 0;
}
第八章(類的繼承)

第八章(類的繼承)

#include <iostream>
#include <string>
using namespace std;
class String {
protected:
    string data;

public:
    String(const string &str) : data(str) {}

    void put() {
        cout << data << endl;
    }

    int length() const {
        return data.length();
    }
};

class EditableString : public String {
public:
    EditableString(const string &str) : String(str) {}

    void insert(int position, char ch) {
        if (position >= 1 && position <= length() + 1) {
            data.insert(data.begin() + position - 1, ch);
        }
    }

    void deleteChar(int position) {
        if (position >= 1 && position <= length()) {
            data.erase(data.begin() + position - 1);
        }
    }

    void replace(int position, char ch) {
        if (position >= 1 && position <= length()) {
            data[position - 1] = ch;
        }
    }
};

int main() {
    EditableString str("1234567890");

    char command;
    int position;
    char ch;

    while (cin >> command) {
        switch (command) {
            case 'i':// 插入
                cin >> position >> ch;
                str.insert(position, ch);
                break;
            case 'd':// 刪除
                cin >> position;
                str.deleteChar(position);
                break;
            case 'r':// 替換
                cin >> position >> ch;
                str.replace(position, ch);
                break;
            default:
                return 0;// 程式結束
        }
        str.put();
    }

    return 0;
}

第八章(多型)

基類指標呼叫派生類物件

#include <cmath>
#include <iostream>
#include <string>
using namespace std;
class Distance {
public:
    int x1, x2, y1, y2;
    virtual int getDis(int x1, int y1, int x2, int y2) = 0;
};
class ManhattanDistance : public Distance {
public:
    virtual int getDis(int x1, int y1, int x2, int y2) {
        return abs(x1 - x2) + abs(y1 - y2);
    }
};
class EuclideanDistance : public Distance {
public:
    virtual int getDis(int x1, int y1, int x2, int y2) {
        return pow(x1 - x2, 2) + pow(y1 - y2, 2);
    }
};
int main() {
    int x1, x2, y1, y2;
    scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
    Distance *p = nullptr;
    p = new ManhattanDistance();
    printf("%d ", p->getDis(x1, y1, x2, y2));
    p = new EuclideanDistance();
    printf("%d", p->getDis(x1, y1, x2, y2));
    return 0;
}

第九章(函式模板)

#include <iostream>
using namespace std;

template<class T>
void Print(T *p, int n) {
    for (int i = 0; i < n; ++i)
        cout << p[i] << " ";
}

template<class T>
void GtLever(T *p, int n, T lever) {
    int j = 0;
    for (int i = 0; i < n; ++i) {
        if (p[i] > lever) {
            swap(p[i], p[j]);
            ++j;
        }
    }
    Print(p, j);
}

int main() {
    string str;
    cin >> str;
    int amount, n;
    cin >> amount >> n;
    if (str == "int") {
        int *data = new int[amount]();
        int lever;
        for (int i = 0; i < amount; ++i) {
            cin >> data[i];
        }
        cin >> lever;
        GtLever(data, n, lever);
        delete[] data;
    } else if (str == "float") {
        float *data = new float[amount]();
        float lever;
        for (int i = 0; i < amount; ++i) {
            cin >> data[i];
        }
        cin >> lever;
        GtLever(data, n, lever);
        delete[] data;
    } else if (str == "char") {
        char *data = new char[amount]();
        char lever;
        for (int i = 0; i < amount; ++i) {
            cin >> data[i];
        }
        cin >> lever;
        GtLever(data, n, lever);
        delete[] data;
    }
    return 0;
}

第九章(類别範本和元素排序)

#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
const int N = 1e5 + 5;
template<typename T>
class Sorter {
public:
    Sorter() {}
    void sortArray(T *arr, int n) {
        for (int i = n; i > 0; i--) {
            bool flag = 0;
            for (int j = 1; j < i; j++) {
                if (arr[j] > arr[j + 1]) {
                    swap(arr[j], arr[j + 1]);
                    flag = 1;
                }
            }
            if (!flag)
                break;
        }
    }
    void printArray(const T *arr, int n) {
        for (int i = 1; i < n; ++i) {
            cout << arr[i] << " ";
        }
        cout << arr[n] << endl;
    }
};
int main() {
    Sorter<int> intSorter;
    int intArr[N];
    int n1;
    cin >> n1;
    for (int i = 1; i <= n1; i++) {
        cin >> intArr[i];
    }
    intSorter.sortArray(intArr, n1);
    Sorter<char> charSorter;
    char charArr[N];
    int n2;
    cin >> n2;
    char x;
    for (int i = 1; i <= n2; i++) {
        cin >> x;
        while (x == ' ' || x == '\n' || x == '\0') cin >> x;
        charArr[i] = x;
    }
    charSorter.sortArray(charArr, n2);
    int n3;
    Sorter<string> stringSorter;
    string stringArr[N];
    cin >> n3;
    string str;
    for (int i = 1; i <= n3; i++) {
        cin >> stringArr[i];
    }
    stringSorter.sortArray(stringArr, n3);
    intSorter.printArray(intArr, n1);
    charSorter.printArray(charArr, n2);
    stringSorter.printArray(stringArr, n3);

    return 0;
}

stl法

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

template<typename T>
class Sorter {
public:
    Sorter() {}

    void sortArray(vector<T> &arr) {
        sort(arr.begin(), arr.end());
    }

    void printArray(const vector<T> &arr) {
        for (const auto &elem: arr) {
            cout << elem << " ";
        }
        cout << endl;
    }
};

int main() {
    Sorter<int> intSorter;
    vector<int> intArr;
    int n;
    cin >> n;
    for (int i = 1, x; i <= n; i++) {
        cin >> x;
        intArr.emplace_back(x);
    }
    intSorter.sortArray(intArr);
    intSorter.printArray(intArr);

    Sorter<char> charSorter;
    vector<char> charArr;
    cin >> n;char x;
    for (int i = 1; i <= n; i++) {
        cin >> x;
        while(x==' '||x=='\n'||x=='\0') cin>>x;
        charArr.emplace_back(x);
    }
    charSorter.sortArray(charArr);
    charSorter.printArray(charArr);

    Sorter<string> stringSorter;
    vector<string> stringArr;
    cin >> n;
    string str;
    for (int i = 1; i <= n; i++) {
        cin >> str;
        stringArr.emplace_back(str);
    }
    stringSorter.sortArray(stringArr);
    stringSorter.printArray(stringArr);

    return 0;
}

第九章(STL基本操作)

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <map>
#include <sstream>
#include <stack>

using namespace std;
#define LL long long
const int N = 1e5;

template<typename T>
inline T read() {
    T x = 0;
    bool f = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = 1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return f ? -x : x;
}

map<int,int>mp;
stack<int>st;
bool flag[N];
int main() {
    int T = read<int>();
    while (T--) {
        int n;
        n = read<int>();
        int x;
        for (int i = 1; i <= n; i++) {
            x=read<int>();
            mp[x]++;
            st.push(x);
            flag[x]=1;
        }
        while(!st.empty()) {
            int x=st.top();
            st.pop();
            if(flag[x]) {
                cout<<x<<" ";
                flag[x]=0;
            }
        }
        cout << endl;
        mp.clear();
    }


    return 0;
}

模擬題一 連結串列

#include <iostream>  
#include <cstdio>  
  
using namespace std;  
  
class Node {  
public:  
    Node *nxt;  
    int val;  
  
    Node() { nxt = nullptr; }  
  
    Node(int x) {  
        nxt = nullptr;  
        val = x;  
    }  
};  
  
class List {  
public:  
    Node *head;  
    Node *tail;  
  
    List() { head = nullptr; };  
  
    ~List() {  
        Node *cur = head;  
        while (cur != nullptr) {  
            Node *next = cur->nxt;  
            delete cur;  
            cur = next;  
        }  
    }  
  
    void Insert(int x) {  
        Node *tmp = new Node(x);  
        if (head == nullptr) {  
            head = tmp;  
            tail = tmp;  
        } else {  
            tail->nxt = tmp;  
            tail = tmp;  
        }  
    }  
  
    void Print() {  
        if (head == nullptr) return;  
        Node *tmp = head;  
        while (tmp != tail) {  
            cout << tmp->val << " ";  
            tmp = tmp->nxt;  
        }  
        cout << tail->val;  
    }  
};  
  
int main() {  
    int N;  
    cin >> N;  
    while (N--) {  
        int m;  
        cin >> m;  
        if (m == 0) {  
            puts("NULL");  
            continue;  
        }  
        List L1, L2;//1奇數  
        int x;  
        for (int i = 1; i <= m; i++) {  
            cin >> x;  
            if (i % 2 != 0) {  
                L1.Insert(x);  
            } else {  
                L2.Insert(x);  
            }  
        }  
        L1.Print();  
        if (L2.head != nullptr) cout << " ";  
        L2.Print();  
        cout << endl;  
  
    }  
    return 0;  
}

模擬題二 繼承和多型

#include <cmath>
#include <iostream>
#include <string>
using namespace std;
enum Encode {
    ASCII,
    Unicode,
    UTF8,
    ANSI
};
Encode trans(int x) {
    switch (x) {
        case 0:
            return ASCII;
            break;
        case 1:
            return Unicode;
            break;
        case 2:
            return UTF8;
            break;
        case 3:
            return ANSI;
            break;
    }
}
class File {
protected:
    string filename;
    long filesize;

public:
    File(const string &name, long fz) : filename(name), filesize(fz) {
    }
    virtual ~File() {}
    virtual void UpdateFile(int encodeFlag) = 0;
    virtual void UpdateFile(int encodeFlag, string new_name) = 0;
    virtual void show() = 0;
};
class TextFile : public File {
private:
    Encode fileEncoder;

public:
    TextFile(const string &name, long size, Encode encoder) : File(name, size), fileEncoder(encoder) {}

    void UpdateFilesize(long size) {
        filesize = size;
    }
    virtual void UpdateFile(int encodeFlag) {
        fileEncoder = trans(encodeFlag);
    }

    virtual void UpdateFile(int encodeFlag, string new_name) {
        fileEncoder = trans(encodeFlag);
        filename = new_name;
    }

    // 顯示檔案資訊
    virtual void show() {
        cout << filename << " " << filesize << " ";
        switch (fileEncoder) {
            case ASCII:
                cout << "ASCII";
                break;
            case Unicode:
                cout << "Unicode";
                break;
            case UTF8:
                cout << "UTF8";
                break;
            case ANSI:
                cout << "ANSI";
                break;
            default:
                cout << "Unknown";
                break;
        }
        cout << endl;
    }
};

int main() {
    string name;
    long siz;
    int enc;
    cin >> name >> siz >> enc;

    TextFile p(name, siz, trans(enc));
    int n;
    cin >> n;
    long data;
    string str;
    for (int i = 1; i <= n; i++) {
        cin >> str;
        switch (str[0]) {
            case 'S':
                p.show();
                break;
            case 's':
                cin >> data;
                // i++;
                p.UpdateFilesize(data);
                break;
            case 'E':
                cin >> data;
                // i++;
                p.UpdateFile(data);
                break;
            case 'e':
                cin >> data;
                cin >> str;
                // i++;
                p.UpdateFile(data, str);
                break;
            default:
                puts("No such function!");
                break;
        }
    }
    return 0;
}

模擬題三 模板類

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

class Student {
private:
    int id;
    string name;
    int score;

public:
    Student(int i = 0, string n = "", int s = 0) : id(i), name(n), score(s) {}
    int getScore() const { return score; }
    bool operator<(const Student &s) const {
        return score < s.score;
    }
    friend istream &operator>>(istream &in, Student &s) {
        return in >> s.id >> s.name >> s.score;
    }
    friend ostream &operator<<(ostream &out, const Student &s) {
        return out << s.id;
    }
};

template<typename T>
class Array {
private:
    int size;
    T *element;

public:
    Array(int s = 0) : size(s), element(new T[s]) {}
    ~Array() {
        delete[] element;
        element = nullptr;
    }
    void sort() {
        for (int i = size - 1; i > 0; i--) {
            for (int j = 0; j < i; j++) {
                if (element[j + 1] < element[j]) {
                    T temp = element[j + 1];
                    element[j + 1] = element[j];
                    element[j] = temp;
                }
            }
        }
    }
    friend istream &operator>>(istream &in, Array<T> &a) {
        for (int i = 0; i < a.size; i++) {
            in >> a.element[i];
        }
        return in;
    }
    friend ostream &operator<<(ostream &out, const Array<T> &a) {
        for (int i = 0; i < a.size; i++) {
            out << a.element[i];
            if (i != a.size - 1) {
                out << " ";
            }
        }
        return out;
    }
};

int main() {
    int n;
    cin >> n;
    Array<int> a1(n);
    cin >> a1;
    a1.sort();
    cout << a1 << endl;
    Array<double> a2(n);
    cin >> a2;
    a2.sort();
    cout << a2 << endl;
    Array<char> a3(n);
    cin >> a3;
    a3.sort();
    cout << a3 << endl;
    Array<Student> a4(n);
    cin >> a4;
    a4.sort();
    cout << a4 << endl;
    return 0;
}

練習一 矩陣運算

二維指標

#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>

using namespace std;
#define LL long long
const int N = 1e5;

template<typename T>
inline T read() {
    T x = 0; bool f = 0; char ch = getchar();
    while (ch < '0' || ch > '9') { if (ch == '-')f = 1; ch = getchar();}
    while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar();}
    return f ? -x : x;
}

int main() {
    int n,m;
    n=read<int>(),m=read<int>();
    int **A=new int *[n];
    for(int i=0;i<n;i++)
        A[i]=new int [m];
    int **B=new int *[n];
    for(int i=0;i<n;i++)
        B[i]=new int [m];

    int **C=new int *[n];
    for(int i=0;i<n;i++)
        C[i]=new int [m];
    
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) 
            A[i][j]=read<int>();
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) 
            B[i][j]=read<int>();
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++) 
            C[i][j]=A[i][j]+B[i][j];
    for(int i=0;i<n;i++) {
        for(int j=0;j<m-1;j++) {
            printf("%d ",C[i][j]);
        }
        printf("%d\n",C[i][m-1]);
    }

    return 0;
}

練習二 字串壓縮

指標

#include <algorithm>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;
#define LL long long
const int N = 1e5;

template<typename T>
inline T read() {
    T x = 0;
    bool f = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = 1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return f ? -x : x;
}
void stringZip(const char *pInputStr, int lInputLen, char *pOutputStr) {
    int cnt = 1;
    pInputStr++;
    for (; *pInputStr <= 'z' && *pInputStr >= 'a'; pInputStr++) {
        if (*pInputStr == *(pInputStr - 1)) {
            cnt++;
        } else {
            if (cnt > 1) {
                *pOutputStr = cnt + '0';
                pOutputStr++;
                cnt = 1;
            }
            *pOutputStr = *(pInputStr - 1);
            pOutputStr++;
        }
    }
    if (cnt > 1) {
        *pOutputStr = cnt + '0';
        pOutputStr++;
        cnt = 1;
    }
    *pOutputStr = *(pInputStr - 1);
    pOutputStr++;
}
int main() {

    char a[1000];//原始字串
    cin >> a;
    int len = strlen(a);
    char b[1000];//壓縮後的字串
    stringZip(a, len, b);
    cout << b << endl;
    return 0;
}

練習三 連結串列

#include <iostream>  
#include <cstdio>  
  
using namespace std;  
  
class Node {  
public:  
    Node *nxt;  
    int val;  
  
    Node() { nxt = nullptr; }  
  
    Node(int x) {  
        nxt = nullptr;  
        val = x;  
    }  
};  
  
class List {  
public:  
    Node *head;  
    Node *tail;  
  
    List() { head = nullptr; };  
  
    ~List() {  
        Node *cur = head;  
        while (cur != nullptr) {  
            Node *next = cur->nxt;  
            delete cur;  
            cur = next;  
        }  
    }  
  
    void Insert(int x) {  
        if (head == nullptr) {  
            Node *tmp = new Node(x);  
            head = tmp;  
            tail = tmp;  
        } else {  
            Node *cur = head;  
            if (x <= head->val) {  
                if (x == head->val) return;  
                Node *tmp = new Node(x);  
                tmp->nxt = head;  
                head = tmp;  
                return;  
            }  
            while (cur->nxt != nullptr && x >= cur->nxt->val) {  
                if (x == cur->nxt->val) return;  
                cur = cur->nxt;  
            }  
            Node *tmp = new Node(x);  
            if (cur == tail) {  
                tail = tmp;  
            }  
            tmp->nxt = cur->nxt;  
            cur->nxt = tmp;  
        }  
    }  
  
    void Print() {  
        if (head == nullptr) return;  
        Node *tmp = head;  
        while (tmp != tail) {  
            cout << tmp->val << " ";  
            tmp = tmp->nxt;  
        }  
        cout << tail->val << endl;  
    }  
};  
  
bool check(int x) {  
    if (x <= 1) return true;  
    if (x == 2) return false;  
    for (int i = 2; i * i <= x; i++) {  
        if (x % i == 0) {  
            return true;  
        }  
    }  
    return false;  
}  
  
int main() {  
    List L;  
    while (1) {  
        int x;  
        cin >> x;  
        if (check(x)) {  
            L.Print();  
            break;  
        }  
        L.Insert(x);  
    }  
    return 0;  
}

練習四 學生成績

#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <sstream>

using namespace std;
#define LL long long
const int N = 1e5;

template<typename T>
inline T read() {
    T x = 0; bool f = 0; char ch = getchar();
    while (ch < '0' || ch > '9') { if (ch == '-')f = 1; ch = getchar();}
    while (ch >= '0' && ch <= '9') { x = x * 10 + ch - '0'; ch = getchar();}
    return f ? -x : x;
}

class Student{
    int id,score;
public:
    Student(){}
    Student(int i,int s):id(i),score(s){}
    Student(const Student& p){
        id=p.id;
        score=p.score;
    }
    bool operator<(const Student &x) const {
        return id<x.id;
    }
    void max(Student *p) {
        Student ans=p[0];
        for(int i=1;i<4;i++) {
            if(p[i].score>ans.score) {
                ans=p[i];
            }
        }
        vector<Student>v;
        for(int i=0;i<4;i++) {
            if(p[i].score==ans.score) {
                v.emplace_back(p[i]);
            }
        }
        sort(v.begin(),v.end());
        for(auto x:v) {
            printf("%d %d\n",x.id,x.score);
        }
    }
};
int main() {
    Student s[4];
    for(int i=0;i<4;i++) {
        int x,y;
        cin>>x>>y;
        s[i]=Student(x,y);
    }
    Student ans;
    ans.max(s);
    return 0;
}

練習題11

設計一個matrix類,並在其中過載:

  • 二元運算子“+”,“-”,“*”,實現矩陣的加減乘;
  • 過載“<<”實現矩陣的輸出運算。
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;
#define LL long long
const int N = 1e5;

template<typename T>
inline T read() {
    T x = 0;
    bool f = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = 1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return f ? -x : x;
}

class Matrix {
    int mat[3][3];

public:
    Matrix() {}
    Matrix(int x) {
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                mat[i][j] = x;
    }
    Matrix(int a[][3]) {
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                mat[i][j] = a[i][j];
    }
    Matrix operator=(Matrix &x) {
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                mat[i][j] = x.mat[i][j];
        return *this;
    }
    Matrix operator+(Matrix &x) {
        Matrix ans;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                ans.mat[i][j] = mat[i][j] + x.mat[i][j];
        return ans;
    }
    Matrix operator-(Matrix &x) {
        Matrix ans;
        for (int i = 0; i < 3; i++)
            for (int j = 0; j < 3; j++)
                ans.mat[i][j] = mat[i][j] - x.mat[i][j];
        return ans;
    }
    Matrix operator*(Matrix &x) {
        Matrix ans(0);
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 3; k++)
                    ans.mat[i][j] = ans.mat[i][j] + mat[i][k] * x.mat[k][j];
            }
        }
        return ans;
    }
    friend ostream &operator<<(ostream &out, Matrix &x) {
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                out << x.mat[i][j] << " ";
            }
            out << endl;
        }
        return out;
    }
};
int main() {
    int a[3][3], b[3][3];
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            a[i][j] = read<int>();
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            b[i][j] = read<int>();
    Matrix A(a);
    Matrix B(b);
    Matrix C = A + B;
    cout << C ;
    Matrix D = A - B;
    cout << D ;
    Matrix E = A * B;
    cout << E ;
    return 0;
}

練習題12

多型,純虛擬函式,虛擬函式

#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>

using namespace std;
#define LL long long
const int N = 1e5;

template<typename T>
inline T read() {
    T x = 0;
    bool f = 0;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-') f = 1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9') {
        x = x * 10 + ch - '0';
        ch = getchar();
    }
    return f ? -x : x;
}

class Shape {
public:
    virtual double getArea() = 0;
    virtual double getPerimeter() = 0;
    virtual ~Shape(){};
};
class Circle : public Shape {
private:
    double r;

public:
    Circle(double x) : r(x) {}
    virtual double getArea() {
        return 3.14 * r * r;
    }
    virtual double getPerimeter() {
        return 6.28 * r;
    }
    double operator-(Circle &x) {
        return fabs(this->getArea() - x.getArea());
    }
    ~Circle() {}
};
class Rectangle : public Shape {
private:
    double a, b;

public:
    Rectangle(double x, double y) : a(x), b(y) {}
    virtual double getArea() {
        return a * b;
    }
    virtual double getPerimeter() {
        return 2 * (a + b);
    }
    ~Rectangle() {}
};

int main() {
    double r1, r2;
    cin >> r1 >> r2;
    if (r1 > 0) {
        Shape *p1 = new Circle(r1);
        cout << p1->getArea() << " " << p1->getPerimeter() << "\n";
        delete p1;
        p1 = nullptr;
    } else {
        cout << "0 0" << endl;
    }
    double x, y;
    cin >> x >> y;
    if (x > 0 && y > 0) {
        Shape *p2 = new Rectangle(x, y);
        cout << p2->getArea() << " " << p2->getPerimeter() << "\n";
        delete p2;
        p2 = nullptr;
    } else {
        cout << "0 0" << endl;
    }
    if (r1 > 0 && r2 > 0) {
        Circle c1(r1), c2(r2);
        double area = c1 - c2;
        cout << area << endl;
    } else {
        cout << "0" << endl;
    }


    return 0;
}

練習題13

連結串列類别範本和節點類别範本 class

#include <algorithm>  
#include <iostream>  
#include <vector>  
  
using namespace std;  
const int N = 100005;  
  
class Node {  
public:  
    int id;  
    char name[20];  
    Node *nxt;  
    Node() {  
        nxt = nullptr;  
    }  
    Node(int x, char *a) {  
        id = x;  
        for (int i = 0; i < 20; i++) name[i] = a[i];  
        nxt = nullptr;  
    }  
};  
class List {  
public:  
    Node *head;  
    List() {  
        head = nullptr;  
    }  
    ~List() {  
        Node *cur = head;  
        while (cur != nullptr) {  
            Node *next = cur->nxt;  
            delete cur;  // 釋放當前節點  
            cur = next;  // 移動到下一個節點  
        }  
    }  
    void insert(char *a, int x) {  
        if (head == nullptr || x < head->id) {  
            Node *tmp = new Node(x, a);  
            tmp->nxt = head;  
            head = tmp;  
            return;  
        }  
        Node *cur = head;  
        while (cur->nxt != nullptr && x > cur->nxt->id) {  
            cur = cur->nxt;  
        }  
        Node *tmp = new Node(x, a);  
        tmp->nxt = cur->nxt;  
        cur->nxt = tmp;  
    }  
    void print() {  
        Node *cur = head;  
        while (cur != nullptr) {  
            cout << cur->name << endl;  
            cur = cur->nxt;  
        }  
    }  
};  
  
  
int main() {  
    char name[20];  
    int id;  
    List li;  
    while(cin>>name>>id) {  
        li.insert(name,id);  
        // if(id==103) break;  
    }  
    li.print();  
    return 0;  
}

模擬考試

題1

img

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;
class Node {
public:
    int val;
    Node *nxt;
    Node() { nxt = nullptr; }
    Node(int x) {
        val = x;
        nxt = nullptr;
    }
    ~Node() {
        if (nxt != nullptr) {
            delete nxt;
            nxt = nullptr;
        }
    }
};
class List {
public:
    Node *head;
    int cnt;

public:
    List() {
        head = new Node();
        cnt = 0;
    }
    void insert(int x) {
        if (head->nxt == nullptr) {
            Node *tmp = new Node(x);
            head->nxt = tmp;
            cnt = 1;
            return;
        }
        Node *cur = head;
        while (cur->nxt != nullptr && x > cur->nxt->val) {
            cur = cur->nxt;
        }
        if (cur->nxt != nullptr && x == cur->nxt->val) return;
        Node *tmp = new Node(x);
        tmp->nxt = cur->nxt;
        cur->nxt = tmp;
        cnt++;
    }
    void del(int id) {
        if (id > cnt) return;
        Node *cur = head;
        for (int i = 1; i < id; i++, cur = cur->nxt);
        cur->nxt = cur->nxt->nxt;
        cnt--;
    }
    void print() {
        if (head->nxt == nullptr) return;
        Node *cur = head->nxt;
        printf("%d", cur->val);
        cur = cur->nxt;
        for (int i = 0; i < cnt - 1; i++, cur = cur->nxt) {
            if (i % 2) {
                printf(" %d", cur->val);
            }
        }
    }
};
int main() {
    // freopen("1.txt", "r", stdin);

    int n;
    cin >> n;
    while (n--) {
        List li;
        int x;
        cin >> x;
        while (x != 0) {
            li.insert(x);
            cin >> x;
        }
        cin >> x;
        li.del(x);
        li.print();
        printf("\n");
    }
    return 0;
}

題2

img

#include <algorithm>
#include <cmath>
#include <iostream>

using namespace std;


class CashSuper {
public:
    virtual int AcceptCash(int m, int q, int a, int b) = 0;
};
class Cash1 : public CashSuper {
public:
    int AcceptCash(int m, int q, int a, int b) {
        return m * q / 10;
    }
};
class Cash2 : public CashSuper {
public:
    int AcceptCash(int m, int q, int a, int b) {
        if (m >= a) {
            m -= b;
        }
        return m;
    }
};
int main() {
    // freopen("1.txt","r",stdin);
    int n;
    cin >> n;
    int m;
    cin >> m;
    int q, a, b;
    for (int i = 1; i <= n; i++) {
        int op;
        cin >> op;
        CashSuper *p = nullptr;
        if (op == 1) {
            p = new Cash1;
            cin >> q;
            printf("%d\n", p->AcceptCash(m, q, 0, 0));
        } else if (op == 2) {
            p = new Cash2;
            cin >> a >> b;
            printf("%d\n", p->AcceptCash(m, 0, a, b));
        } else {
            p = new Cash1;
            cin >> q;
            m = p->AcceptCash(m, q, 0, 0);
            p = new Cash2;
            cin >> a >> b;
            printf("%d\n", p->AcceptCash(m, 0, a, b));
        }
    }

    return 0;
}

題3

有一組卡牌,上面寫著113或者AM,你隨機抽分到了其中若干張卡牌,其中兩張數字相同或者字母相同的卡牌可以配對。你需要將分到的卡牌配對,然後棄置這些成對的牌,最終將剩餘的卡牌按照數字的升序或字母表的順序輸出。

請編寫實現類似功能的模板類,要求:模組接受的資料型別為int型別和char型別,用以儲存為數字113或者字元AM,玩家分到的手牌上限是20張,玩家初始狀態為不超過20的隨機數量的卡牌,在棄置所有配對牌(match方法)之後,將剩餘手牌按從小到大輸出展示(show方法)。

Class myCards
T cards[MaxSize];
Int count;
MyCards(T*a,int size){//建構函式,傳入初始手牌陣列
……
Match();;//棄置配對牌操作
//展示手牌操作Show();

輸入:

輸入三行,第一行為一個數字1或者0,1表示接下來輸入的卡牌為數字1到13;0表示字母A到M,第二行為給使用者分發的初始手牌數量為1到20,第三行為給使用者分發的手牌。

輸出:

輸出為兩行,第一行為棄置配對牌之後的剩餘手牌數量,第二行為棄置配對牌之後的手牌輸出,用空格分隔,行尾無空格。當剩餘手牌數量為0時,第二行輸出WIN。

樣例輸入1:

1
4
3 13 3 13

樣例輸出1:

0
WIN

樣例輸入2:

1
4
3 1 3 13

樣例輸出2:

2
1 13

注意:必須實現類别範本,否則計0分

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;
bool flag[21];
template<class T>
class MyCards {
public:
    MyCards(T *a, int siz) {
        n = siz;
        for (int i = 1; i <= n; i++)
            card[i] = a[i];
    }
    void match() {
        for (int i = 1; i <= n; i++)
            for (int j = i + 1; j <= n; j++) {
                if (card[i] == card[j]) {
                    flag[i] = flag[j] = 1;
                }
            }
        T temp[21];
        int cnt = 0;
        for (int i = 1; i <= n; i++)
            if (!flag[i])
                temp[++cnt] = card[i];
        n = cnt;
        for (int i = 1; i <= cnt; i++)
            card[i] = temp[i];
    }
    void show() {
        if(n==0) {
            printf("0\n");
            puts("WIN");
            return;
        }
        for (int i = n; i > 0; i--) {
            for (int j = 1; j < i; j++) {
                if (card[j] > card[j + 1]) {
                    T tmp = card[j];
                    card[j] = card[j + 1];
                    card[j + 1] = tmp;
                }
            }
        }
        cout<<n<<endl;
        for(int i=1;i<n;i++)
            cout<<card[i]<<" ";
        cout<<card[n];
    }

private:
    T card[21];
    int n;
};
int main() {
    // freopen("1.txt", "r", stdin);
    int op;
    cin >> op;
    int n;
    cin >> n;
    if (op == 1) {
        int val[21];
        for (int i = 1; i <= n; i++)
            cin >> val[i];
        MyCards<int> my(val, n);
        my.match();
        my.show();
    } else {
        char data[21];
        for (int i = 1; i <= n; i++)
            cin >> data[i];
        MyCards<char> my2(data, n);
        my2.match();
        my2.show();
    }

    return 0;
}

相關文章