algorithm

[c++] 연속부분증가수열, Jolly jumpers

tonirr 2020. 12. 7. 23:33
  • 연속부분증가수열
// 내가 짠코드
#include <iostream>
#include <vector>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
	//freopen("input.txt", "rt", stdin);
	int n, i, cnt=1, max=-2147000000;
	scanf("%d", &n);
	std::vector<int> a(n);
	for(i=1; i<=n; i++){
		scanf("%d", &a[i]);
	}
	for(i=1; i<=n-1; i++){
		if(a[i] <= a[i+1]){
			cnt++;
			if(cnt > max){
				max=cnt;
			}
		} else {
			cnt=1;
		}
	}
	printf("%d", max);
	return 0;
}

// 참고한 코드
#include <iostream>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
	//freopen("input.txt", "rt", stdin);
	int n, i, pre, now, cnt=1, max=-2147000000;
	scanf("%d", &n);
	scanf("%d", &pre);
	for(i=2; i<=n; i++){
		scanf("%d", &now);
		if(pre <= now){
			cnt++;
			if(cnt > max) max=cnt;
		} else cnt=1;
		pre=now;
	}
	printf("%d", max);
	return 0;
}
  • 참고한 코드에서는 배열에 무조건 담지 않고 for문을 한개만 이용해서 문제를 품
    • 연속적으로 나오는 수를 단순 비교하면 배열에 담는 것을 먼저 생각하기 보다는 하나씩 읽어 나가는 것을 방법을 고려해보기

 

  • Jolly jumpers
#include <iostream>
#include <vector>
#include <algorithm>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
	//freopen("input.txt", "rt", stdin);
	int n, i, pre, now, diff, cnt=1, max=-2147000000;
	scanf("%d", &n);
	scanf("%d", &pre);
	std::vector <int> a(n);
	for(i=2; i<=n; i++){
		scanf("%d", &now);
		diff = abs(now - pre);
		if(diff>0 && diff<n && a[diff]==0){
			a[diff]=1;
		}else {
			printf("NO\n");
			return 0;
		}
		pre=now;
	}
	printf("YES\n");
	return 0;
}