子字符串问题

链接:https://www.patest.cn/contests/gplt/L1-006

L1-006. 连续因子

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

一个正整数N的因子中可能存在若干连续的数字。例如630可以分解为3*5*6*7,其中5、6、7就是3个连续的数字。给定任一正整数N,要求编写程序求出最长连续因子的个数,并输出最小的连续因子序列。

输入格式:

输入在一行中给出一个正整数N(1<N<231)。

输出格式:

首先在第1行输出最长连续因子的个数;然后在第2行中按“因子1*因子2*……*因子k”的格式输出最小的连续因子序列,其中因子按递增顺序输出,1不算在内。

输入样例:
630
输出样例:
3
5*6*7

题解:要理解子字符串的一些规律:子字符串是从一个字符串中取出任意大小的字符,模拟这个过程:该字符串的每个字符为子字符串的首字符,然后从该首字符开始向后添加字符,当遇到满足的条件时,进行相应的更新操作。


#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
#include<climits>
#include<cmath>

using namespace std;

int main()
{
	int n;
	while(scanf("%d",&n) != EOF)
	{
		int k = 0,count = 0;
		for(int i = 2; i < sqrt(n); i++)
		{
			long long  ans = 1;//注意相乘可能会溢出! 
			for(int j = i; ans*j <= n; j++)
			{
				ans = ans*j;
				if(n%ans == 0)
				{
					if(count < j-i+1)
					{
						k = i;
						count = j-i+1;
					}
				}
			}
		}
		if(count == 0)
			printf("1\n%d\n",n);
		else
		{
			printf("%d\n",count);
			count = count+k;
			for(int i = k; i < count-1; i++)
			{
				printf("%d*",i);
			}
			printf("%d\n",count-1);	
		}
	 } 
 return 0;
}


链接:https://www.nowcoder.com/acm/contest/91/L

来源:牛客网

时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 131072K,其他语言262144K
64bit IO Format: %lld

题目描述

给一个数组 a,长度为 n,若某个子序列中的和为 K 的倍数,那么这个序列被称为“K 序列”。现在要你 对数组 a 求出最长的子序列的长度,满足这个序列是 K 序列。 

输入描述:

第一行为两个整数 n, K, 以空格分隔,第二行为 n 个整数,表示 a[1] ∼ a[n],1 ≤ n ≤ 105 , 1 ≤ a[i] ≤ 109 , 1 ≤ nK ≤ 107

输出描述:

输出一个整数表示最长子序列的长度 m

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<vector>

using namespace std;

int main()
{
	int n,k,a[100005];
	long long sum,ans;
	while(scanf("%d%d",&n,&k) != EOF)
	{
		ans = 0;
		for(int i = 0; i < n; i++)
			scanf("%d",&a[i]);
		for(int i = 0; i < n; i++)
		{
			long long sum = 0;
			for(int j = i+ans; j < n; j++)//如果令j=i;则会超时!!!!!! 
			{
				sum += a[j];
				if(sum % k == 0 && sum > k)
				{
					if(j-i+1 > ans)
						ans = j-i+1;
				} 
//				if(ans > n-i) 等同于上面的j = i+ans;
//					break; 
			}
		}
		printf("%lld\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cutedumpling/article/details/79955152
今日推荐