D - Wave HDU - 6570(暴力模拟 / 简单dp)

Avin is studying series. A series is called “wave” if the following conditions are satisfied:

  1. It contains at least two elements;
  2. All elements at odd positions are the same;
  3. All elements at even positions are the same;
  4. Elements at odd positions are NOT the same as the elements at even positions.
    You are given a series with length n. Avin asks you to find the longest “wave” subseries. A subseries is a subsequence of a series.
    Input
    The first line contains two numbers n, c (1 ≤ n ≤ 100, 000, 1 ≤ c ≤ 100). The second line contains n integers whose range is [1, c], which represents the series. It is guaranteed that there is always a “wave” subseries.
    Output
    Print the length of the longest “wave” subseries.
    Sample Input
    5 3
    1 2 1 3 2
    Sample Output
    4

题意:
在输入的n个数中按顺序选出一些数,组成一个波,这个波中的所有奇数位元素相同,所有偶数位置的元素都是相同的,奇数位置的元素与偶数位置的元素不同。

题解:
最开始想得就是暴力模拟,一直怕超时不敢写,想了很久没想出其他办法,结果去看其它的博客,就是暴力模拟解决。。。。于是A掉本题(代码有注释)

在解决的过程中发现了大佬用dp也能过,思想为:每次更新的 i,j 序列长度为 j,i序列长度+1,例如波 1 2 1为dp[1][2]=3,当波更新为 1 2 1 2时,只需要dp[2][1]=dp[1][2]=3+1,在更新过程中不断取最大值

暴力模拟AC:

#include"iostream"
#include"string"
#include"vector"
#include"algorithm"
using namespace std;
int main()
{
	int n,c;
	vector s[105];//储存输入的每个数所在的位置
	while(cin>>n>>c)
	{
		for(int i=0;i<=105;i++){
			s[i].clear();
		}
		for(int i=1;i<=n;i++){
			int x;
			cin>>x;
			s[x].push_back(i);
		}
		int maxn=0;//最大波长
		for(int i=1;i<=c;i++){
			for(int j=1;j<=c;j++){//模拟所有情况
				if(i==j){
					continue;
				}
				int cnt=0,next=0,v1=0,v2=0;//波的长度,波上一个位置,s[i]下标,s[j]下标
				int leni=s[i].size();
				int lenj=s[j].size();
				while(1){
					while(s[i][v1]

dpAC:

#include"iostream"
#include"string.h"
#include"algorithm"
using namespace std;
int main()
{
	int n,c,x,dp[105][105];
	while(cin>>n>>c)
	{
		memset(dp,0,sizeof(dp));
		int maxn=0;
		for(int i=1;i<=n;i++){
			cin>>x;
			for(int j=1;j<=c;j++){
				dp[x][j]=dp[j][x]+1;//dp公式
				if(x!=j){//奇偶位置元素不能相同
					maxn=max(maxn,dp[x][j]);
				}
			}
		}
		cout<

你可能感兴趣的:(DP-动态规划)