0%

題目來源:106東區學科能力競賽

gcd轉lcm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<bits/stdc++.h>
using namespace std;

int dayInM[12]={31,28,31,30,31,30,31,31,30,31,30,31};

void check(int y){
if((y%4==0 && y%100!=0) || y%400==0){
dayInM[1]=29;
}else{
dayInM[1]=28;
}
return;
}

int gcd(int a,int b){
if(a%b==0){
return b;
}else{
return gcd(b,a%b);
}
}

int main(){
int n;
scanf("%d",&n);

int dt[500];
for(int i=0;i<n;i++){
scanf("%d",dt+i);
}

int y,m,d;
scanf("%d/%d/%d",&y,&m,&d);
for(int i=0;i<n-1;i++){
int d=gcd(dt[i],dt[i+1]);
int min=d*dt[i]/d*dt[i+1]/d;
dt[i+1]=min;
}

d+=dt[n-1];

check(y);
while(d>dayInM[m-1]){
d-=dayInM[m-1];
m++;
if(m>12){
m=1;
y++;
}
check(y);
}
printf("%4d/%02d/%02d",y,m,d);
return 0;
}
閱讀全文 »

題目連結:Sorting: Bubble Sort | HackerRank

這題雖然有更好的算法(merge sort+反序數對),但用氣泡就可以了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void countSwaps(vector<int> a) {
int ct=0;
for(int i=0;i<a.size();i++){
for (int j=0;j<a.size()-1;j++){
if (a[j]>a[j+1]){
ct++;
swap(a[j],a[j+1]);
}
}
}
cout<<"Array is sorted in "<<ct<<" swaps."<<"\n";
cout<<"First Element: "<<a[0]<<"\n";
cout<<"Last Element: "<<a[a.size()-1];
return;
}
閱讀全文 »

題目連結:2D Array - DS | HackerRank

如題,二維陣列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int hourglassSum(vector<vector<int>> arr) {
int mx=-0x3f3f3f3f;
for(int i=0;i<arr.size()-2;i++){
for(int j=0;j<arr[i].size()-2;j++){
int sum=arr[i][j]+
arr[i][j+1]+
arr[i][j+2]+
arr[i+1][j+1]+
arr[i+2][j]+
arr[i+2][j+1]+
arr[i+2][j+2];
mx=max(mx,sum);
}
}
return mx;
}
閱讀全文 »

題目連結:Hash Tables: Ransom Note | HackerRank

這APCS應該不會考吧?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void checkMagazine(vector<string> magazine, vector<string> note) {
unordered_map<string,int> m,n;
for(auto a:magazine){
m[a]++;
}
for(auto a:note){
n[a]++;
}

for(auto a:n){
if(m[a.first]<n[a.first]){
cout<<"No\n";
return;
}
}
cout<<"Yes\n";
}
閱讀全文 »

題目連結:Array Manipulation | HackerRank

只要算開始與結束即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
struct edge{
int s,e,c;
};

long arrayManipulation(int n, vector<edge> q) {
long mx=0,now=0;
sort(q.begin(),q.end(),[](edge a,edge b){
return a.s<b.s;
});
vector<edge> bk(q);
sort(bk.begin(),bk.end(),[](edge a,edge b){
return a.e<b.e;
});

int i=0;
for(auto a:q){
now+=a.c;
while(i<q.size() && a.s>bk[i].e){
now-=bk[i].c;
i++;
}
mx=max(mx,now);
}
return mx;
}
閱讀全文 »

題目連結:Minimum Swaps 2 | HackerRank

注意算完(算之前亦可)要將兩數交換

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int minimumSwaps(vector<int> arr) {
vector<int> o(arr);
sort(o.begin(),o.end());
int ct=0,update=0;
int m[100010]{0};
for(int i=0;i<arr.size();i++){
if(arr[i]!=o[i]){
swap(arr[i],arr[arr[i]-1]);
ct++;
i--;
}
}
return ct;
}
閱讀全文 »