algorithm

[c++] 카드게임, 온도의 최대값

tonirr 2020. 12. 6. 16:55
  • 카드게임
#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 i, a[11], b[11], a_cnt=0, b_cnt=0, lw=0;
	for(i=1; i<=10; i++){
		scanf("%d", &a[i]);	
	}
	for(i=1; i<=10; i++){
		scanf("%d", &b[i]);
	}
	for(i=1; i<=10; i++){
		if(a[i]==b[i]) {
			a_cnt++;
			b_cnt++;	
		}
		else if(a[i] > b[i]) {
			a_cnt+=3;
			lw=1;	
		}
		else {
			b_cnt+=3;
			lw=2;	
		}
	}
	printf("%d %d\n", a_cnt, b_cnt);
	if(a_cnt == b_cnt) {
		if(lw==1){
			printf("A");
		}else if(lw==2){
			printf("B");
		} else if(lw==0){
			printf("D");
		}
	}
	else if(a_cnt > b_cnt) printf("A"); 
	else printf("B");
	return 0;
}

 

  • 온도의 최대값
#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, k, i, sum=0, max=-2147000000;
	scanf("%d %d", &n, &k);
	std::vector<int> a(n);
	for(i=0; i<n; i++){
		scanf("%d", &a[i]);
	}
	for(i=0; i<k; i++){
		sum+=a[i];
	}
	for(i=k; i<n; i++){
		sum=sum+(a[i]-a[i-k]);
		if(max<sum) max=sum;
	}
	printf("%d", max);
	return 0;
}
  • 이중 for문을 사용해서도 풀 수 있는 문제이지만 for문을 하나만 사용해서 풀 수 있어야 함
  • a배열의 i인덱스를 활용해서 a[i]값을 sum에 합하고 a[i-k]값을 sum에서 빼주면 다음 sum값이 도출됨