lecture/algorithm - c++
[c++] 공주구하기, 멀티 태스킹
tonirr
2020. 12. 27. 18:09
공주구하기
<정답 코드>
#include <iostream>
#include <vector>
#include <algorithm>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main() {
//freopen("input.txt", "rt", stdin);
int n, k, i, pos=0, bp=0, cnt=0;
scanf("%d %d", &n, &k);
vector<int> prince(n+1);
while(1){
pos++;
if(pos>n) pos=1;
if(prince[pos]==0){
cnt++;
if(cnt==k){
prince[pos]=1;
cnt=0;
bp++;
}
}
if(bp==n-1) break;
}
for(i=1; i<=n; i++){
if(prince[i]==0){
printf("%d ", i);
break;
}
}
return 0;
}
<내가푼코드>
#include <iostream>
#include <vector>
#include <algorithm>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main() {
freopen("input.txt", "rt", stdin);
int n, k, i, j, cnt, res;
scanf("%d %d", &n, &k);
vector<int> a(n+1);
for(i=1; i<=n; i++){
a[i]=i;
}
j=0;
i=0;
cnt=1;
while(cnt<=n){
if(i>n){
i=1;
}else {
i++;
}
if(a[i]!=0){
j++;
}
if(j==k){
cnt++;
res=a[i];
a[i]=0;
j=0;
}
}
printf("%d ", res);
return 0;
}
멀티태스킹
<내가짠것>
#include <iostream>
#include <vector>
#include <algorithm>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main() {
freopen("input.txt", "rt", stdin);
int n, k, i, res, pos=0, bp=0, cnt=0, chk=0;
scanf("%d", &n);
vector<int> a(n+1);
for(i=1; i<=n; i++){
scanf("%d ", &a[i]);
}
scanf("%d", &k);
i=0;
pos=0;
while(1){
i++;
printf("\ni: %d, ", i);
if(pos==n){
pos=0;
}
while(1){
pos++;
printf("pos: %d, ", pos);
if(a[pos]!=0){
a[pos]--;
printf("a[pos]: %d, ", a[pos]);
break;
}else {
if(pos==n){
break;
}
}
}
if(i==k) {
res=pos;
break;
}
}
if(a[n]==0) res=-1;
printf("%d ", res);
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main() {
//freopen("input.txt", "rt", stdin);
int n, k, i, res, pos=0, bp=0, cnt=0, tot=0;
scanf("%d", &n);
vector<int> a(n+1);
for(i=1; i<=n; i++){
scanf("%d ", &a[i]);
tot+=a[i];
}
scanf("%d", &k);
if(tot<=k) {
printf("-1");
return 0;
}
pos=0;
while(1){
pos++;
if(pos>n){
pos=1;
}
if(a[pos]==0) continue;
a[pos]--;
cnt++;
if(cnt==k) break;
}
while(1){
pos++;
if(pos>n) pos=1;
if(a[pos]!=0) break;
}
printf("%d ", pos);
return 0;
}