HDU5211Mutiple

思路:利用筛法,求出每一个数的倍数,然后在其中求下标最小的。

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
const int maxn = 10010;
const int INF = 0x7fffff;

int gn;
int fun[maxn];
int chose[maxn];
vector<int> Hash[maxn];
vector<int> data;

void work() {
	for(int i = 1; i <= 10000; i++) {
		Hash[i].clear();
	}
	for(int i = 1; i <= 10000; i++) {
		if(chose[i] == 1) {
			for(int j = i+i; j <= 10000; j += i) {
				if(chose[j] == 1) {
				    if(fun[j] > fun[i]) {
                        Hash[i].push_back(fun[j]);
				    }
				}
			}
		}
	}
}
int getResult() {
	int res = 0, d = 0;
	int minvalue = -1;
	for(int i = 0; i < (int)data.size(); i++) {
		d = data[i];
		minvalue = INF;
		for(int j = 0; j < (int)Hash[d].size(); j++) {
			minvalue = min(minvalue, Hash[d][j]);
		}
		if(minvalue != INF) res += minvalue;
	}
	return res;
}

int main()
{
	int read;
	while(scanf("%d", &gn) != EOF) {
		memset(fun, -1, sizeof(fun));
		memset(chose, 0, sizeof(chose));
		data.clear();
		for(int i = 1; i <= gn; i++) {
			scanf("%d", &read);
			fun[read] = i;
			chose[read] = 1; //exist
			data.push_back(read);
		}
		work();
		int res = getResult();
		printf("%d\n", res);
	}
	return 0;
}
时间: 2024-11-13 08:38:16

HDU5211Mutiple的相关文章