algorithm

[c++] Least Recently Used, Inversion Sequence

tonirr 2020. 12. 22. 00:29
  • Least Recently Used
#include <iostream>

/* 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 s, n, i, j, pos;
	int c[10], a[1000];
	scanf("%d", &s);
	scanf("%d", &n);
	
	for(i=0; i<n; i++){
		scanf("%d", &a[i]);
	}
	
	for(i=0; i<n; i++){
		pos = -1;
		for(j=0; j<s; j++){
			if(a[i]==c[j]) pos = j;
		}
		
		if(pos==-1){
			for(j=s-1; j>=0; j--){
				c[j+1]=c[j];
			}
			
		} else {
			for(j=pos-1; j>=0; j--){
				c[j+1]=c[j];
			}
			
		}
		c[0]=a[i];
	}

	for(i=0; i<s; i++){
		printf("%d ", c[i]);
	}
	return 0;
}

 

  • Inversion Sequence
#include <iostream>

/* 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, i, j;
	int a[100], b[100];
	scanf("%d", &n);
	
	for(i=1; i<=n; i++){
		scanf("%d", &a[i]);
	}
	
	for(i=n; i>=1; i--){
		for(j=1; j<=a[i]; j++){
			b[i+j-1]=b[i+j];
		}
		b[i+j-1] = i;
	}

	for(i=1; i<=n; i++){
		printf("%d ", b[i]);
	}
	return 0;
}