UVA 1481 - Genome Evolution(枚举技巧)

Xi, a developmental biologist is working on developmental distances of chromosomes. A chromosome, in the Xi‘s simplistic view, is a permutation from n genes numbered 1 to n. Xi is working on an evolutionary distance metric between two chromosomes. In Xi‘s theory of evolution any subset of genes lying together in both chromosomes is a positive witness for chromosomes to be similar.

A positive witness is a pair of sequence of the same length A and A‘, where A is a consecutive subsequence of the first chromosome, A‘ is a consecutive subsequence of the second chromosome, and A is a permutation ofA‘. The goal is to count the number of positive witnesses of two given chromosomes that have a length greater than one.

Input 

There are several test case in the input. Each test case starts with a line containing the number of genes(2UVA 1481 - Genome Evolution(枚举技巧)nUVA 1481 - Genome Evolution(枚举技巧)3000). The next two lines contain the two chromosomes, each as a list of positive integers. The input terminates with a line containing ``0‘‘ which should not be processed as a test case.

Output 

For each test case, output a single line containing the number of positive witness for two chromosomes to be similar.

Sample Input 

4 
3 2 1 4 
1 2 4 3 
5 
3 2 1 5 4
3 2 1 5 4
0

Sample Output 

3 
10

题意:说白了就是求两个集合有几个相同的连续子集。

思路:记录下第二个集合每个数的位置。然后去枚举第一个集合。把子集内的数字位置的Max和Min记录下来,然后如果Max - Min + 1 == len说明集合长度相同。在记录过程中,利用了类似前缀和的思想,复杂度为O(n^2)。

代码:

#include <stdio.h>
#include <string.h>
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))

const int N = 3005;

int n, a[N], vis[N];

void init() {
	int num;
	for (int i = 0; i < n; i++)
		scanf("%d", &a[i]);
	for (int j = 0; j < n; j++) {
		scanf("%d", &num);
		vis[num] = j;
	}
}

int solve() {
	int ans = 0;
	for (int i = 0; i < n; i++) {
		int Max = vis[a[i]], Min = vis[a[i]], len = 1;
		for (int j = i + 1; j < n; j++) {
			Max = max(Max, vis[a[j]]);
			Min = min(Min, vis[a[j]]);
			len++;
			if (Max - Min + 1 == len) {
				ans++;
			}
		}
	}
	return ans;
}

int main() {
	while (~scanf("%d", &n) && n) {
		init();
		printf("%d\n", solve());
	}
	return 0;
}


UVA 1481 - Genome Evolution(枚举技巧)

上一篇:MySQL常用命令大全


下一篇:Mysql 数据库备份脚本