HDU 1795--The least one【二分 || 暴力】

The least one

Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 394    Accepted Submission(s): 141


Problem Description
  In the RPG game “go back ice age”(I decide to develop the game after my undergraduate education), all heros have their own respected value, and the skill of killing monsters is defined as the following rule: one hero can kill the monstrers whose respected values are smaller then himself and the two respected values has none common factor but 1, so the skill is the same as the number of the monsters he can kill. Now each kind of value of the monsters come. And your hero have to kill at least M ones. To minimize the damage of the battle, you should dispatch a hero with minimal respected value. Which hero will you dispatch ? There are Q battles, in each battle, for i from 1 to Q, and your hero should kill Mi ones at least. You have all kind of heros with different respected values, and the values(heros’ and monsters’) are positive.
 

Input
  The first line has one integer Q, then Q lines follow. In the Q lines there is an integer Mi, 0<Q<=1000000, 0<Mi<=10000.
 

Output
  For each case, there are Q results, in each result, you should output the value of the hero you will dispatch to complete the task.
 

Sample Input
   
   
   
   
2 3 7
 

Sample Output
   
   
   
   
5 11
 

题比较水,暴力直接就可以过,还以为会超时
#include <cstdio>
#include <cstring>

int str[1000100] = {1, 1, 0};
int a[1000100];
int k;
void prime(){
	int i, j;
	for(int i = 2; i * i < 1000100; ++i){
		if(!str[i]){
			for(int j = i * 2; j < 1000100; j = j + i)
			str[j] = 1;
		}
	}
	return ;
}

void change(){
	k = 0;
	for(int i = 0; i <= 1000100; ++i){
		if(!str[i])
			a[++k] = i;
	}
	return ;
}

int main (){
	int T;
	prime();
	change();
	int i;
	scanf("%d", &T);
	while(T--){
		int n;
		scanf("%d", &n);
		for(i = 1; i <= k; ++i)
			if(a[i] > n) 
				break;
		printf("%d\n", a[i]);
	}
	return 0;
}


又用二分写了一遍

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int str[10100] = {1, 1, 0};
int a[10100];
int k;
void prime(){
	int i, j;
	for(int i = 2; i * i < 10100; ++i){
		if(!str[i]){
			for(int j = i * i; j < 10100; j = j + i)
			str[j] = 1;
		}
	}
	return ;
}

void change(){
	k = 0;
	for(int i = 0; i <= 10100; ++i){
		if(!str[i])
			a[++k] = i;
	}
	return ;
}

int main (){
	int T;
	prime();
	change();
	scanf("%d", &T);
	while(T--){
		int n;
		scanf("%d", &n);
	int l = 1, r = k;
		while(  r >= l){
			int mid = (l + r) / 2;

			if(a[mid] > n)
				r = mid - 1;
			else
				l = mid + 1;
		}
		printf("%d\n" , a[l]);
	}
	return 0;
}


你可能感兴趣的:(HDU 1795--The least one【二分 || 暴力】)