Algorithm/etc
LRU( Least Recently Used) cpp 구현
DingCoDing
2022. 1. 6. 14:31
반응형
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
int a[11];
using namespace std;
int main() {
int s, n, i,j;
scanf("%d",&s);
scanf("%d",&n);
for(i=0;i <n;i++){
int val , idx;
scanf("%d",&val);
bool isin = false;
for(j=0; j<s; j++){
if(a[j]==val){
isin = true;
idx = j;
break;
}
}
// cache hit // 있으면 그 숫자만 앞으 로
if(isin){
for(j=idx; j>=1; j--){
a[j] = a[j-1];
a[j-1] = val;
}
}
else{
// cache miss // 없으면 다 뒤로 밀고 맨앞에
for(j=s-1; j>=1; j--){
a[j] = a[j-1];
}
a[0] = val;
}
for(j=0; j<s; j++){
printf("%d ", a[j]);
}
printf("\n");
}
return 0;
}
----
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
int c[11];
using namespace std;
int main() {
int s,n,a, i,j,pos;
scanf("%d %d", &s, &n);
for(i=1; i<=n; i++){
scanf("%d", &a);
pos=-1;
for(j=0;j<s;j++)if(c[j]==a) pos=j;
if(pos==-1){
for(j=s-1; j>=1; j--) c[j]=c[j-1];
}
else{
for(j=pos; j>=1; j--) c[j]=c[j-1];
}
c[0] = a;
}
for(i=0; i<s; i++){
printf("%d ", c[i]);
}
}반응형