2016級計算機C++助教工作(12) 第二次上機解題報告

A.   Brainman

冒泡排序,平方的複雜度能過,循環N次,每次判斷相鄰兩個數是否要交換,統計次數即可

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int num[1001];

int main(){
	int t,n;
	cin>>t;
	for(int tt = 1; tt <= t; tt++){
		cin>>n;
                 
		for(int i = 0;i < n; i++){
			cin>>num[i];
		}
		int ans = 0;
		for(int i = 0;i < n; i++){
			for(int j = 0;j < n -1 ; j++){
				if(num[j] > num[j+1]){
					swap(num[j],num[j+1]);
					ans++;
				}
			}
		}
		printf("Scenario #%d:\n",tt);
		cout<<ans<<endl<<endl;
	}
	return 0;
}

B.   Eazzzzzy

根據三種情況,分別輸出圖形接口,每一行的輸出格式都是能算出的

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


int main(){
    int t,n,c;
    while(cin>>t){
        if(t == -1) return 0;
        if(t == 1){
            cin>>n;
            for(int i = 0;i < n; i++){
                for(int j = 0;j < n - i - 1; j++)
                    cout<<" ";
                for(int j = 0;j < i*2+1; j++)
                    cout<<"*";
                cout<<endl;

            }
        }
        if(t == 2){
            cin>>n>>c;
            for(int i = 0;i < c; i++){
                for(int j = 0;j < c - i - 1;j++)
                    cout<<" ";
                for(int j = 0;j < n; j++)
                    cout<<"*";
                cout<<endl;
            }
        }
        if(t == 3){
            cin>>n>>c;
            for(int i = 0;i < c; i++){
                for(int j = 0;j < n; j++)
                    cout<<"*";
                cout<<endl;

            }

        }
        cout<<endl;
    }
}

C.   Primary Arithmetic

按位加法,統計進位數即可

#include <iostream>
using namespace std;

int main()
{
    int  a,b,c,d;
    while(cin>>a>>b){
        if(a==0&&b==0)
            break;

        c=d=0;
        while(a!=0 || b!=0 ){
            c = a%10 + b%10 + d;
            a = a/10;
            b = b/10;
            if(c>9){
                d++;
            }
        }
        if(d==0)
            cout<<"No carry operation."<<endl;
        else if(d==1)
            cout<<"1 carry operation."<<endl;
        else
            cout<<d<<" carry operations."<<endl;

    }
}

D.   Binary Numbers

輸出二進制數中1的位置

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


int main(){
  int t,n;
  cin>>t;
  while(t--){
    cin>>n;
    int f = 0,p = 0;
    while(n){
        if(n % 2 == 1){
            if(f)cout<<" ";
            cout<<p;
            f = 1;
        }
        p++;
        n /= 2;
    }
    cout<<endl;

  }
}

E.   Digital Roots

實際把所有數字加起來對9取模即可,特判結果是0的情況,

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

char x[1000];
int main(){
  int n;
  while(cin>>x){
    if(x[0] == '0')break;
    int len = strlen(x);
    int t = 0;
    for(int i = 0;i < len; i++)
        t += x[i] - '0';
    t = t % 9;
    if(t == 0) t = 9;
    cout<<t<<endl;
  }
  return 0;
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章