选数字

题意

当给定一个序列 a[0],a[1],a[2],...,a[n-1]和一个整数 K 时,我们想找出,有多少子序列满足这么一个条件:把当前子序列里面的所有元素乘起来恰好等于K。


思路

比较裸的背包,将k质因数分解即可。

代码

#include <bits/stdc++.h>

using namespace std;

namespace StandardIO {

	template<typename T>inline void read (T &x) {
		x=0;T f=1;char c=getchar();
		for (; c<'0'||c>'9'; c=getchar()) if (c=='-') f=-1;
		for (; c>='0'&&c<='9'; c=getchar()) x=x*10+c-'0';
		x*=f;
	}

	template<typename T>inline void write (T x) {
		if (x<0) putchar('-'),x*=-1;
		if (x>=10) write(x/10);
		putchar(x%10+'0');
	}

}

using namespace StandardIO;

namespace Project {
	
	const int N=50005;
	
	int n,k;
	int cnt;
	int head[N];
	struct node {
		int to,next;
	} edge[N<<1];
	int tot;
	int dep[N],leaf[N],vis[N],f[N];
	
	inline bool cmp (int x,int y) {
		return (dep[x]==dep[y])?x<y:dep[x]>dep[y];
	}
	
	inline void add (int a,int b) {
		edge[++cnt].to=b,edge[cnt].next=head[a],head[a]=cnt;
	}
	void dfs (int now,int fa) {
		dep[now]=dep[fa]+1,f[now]=fa;
		int tot_son=0;
		for (register int i=head[now]; i; i=edge[i].next) {
			int to=edge[i].to;
			if (to==fa) continue;
			++tot_son,dfs(to,now);
		} 
		if (!tot_son) leaf[++tot]=now;
	}

	inline void MAIN () {
		read(n),read(k);
		for (register int i=1,x; i<=n-1; ++i) {
			read(x);
			add(x,i),add(i,x);
		}
		dfs(k,k);
		sort(leaf+1,leaf+tot+1,cmp);
		for (register int i=1; i<=tot; ++i) {
			int now=leaf[i],ori=now;
			dep[now]=0;
			while (!vis[now]) {
				vis[now]=1,now=f[now],++dep[ori];
				if (now==k) break;
			}
		}
		sort(leaf+1,leaf+tot+1,cmp);
		write(k),putchar('\n');
		if (leaf[1]==0) return;
		for (register int i=1; i<=tot; ++i) {
			write(leaf[i]),putchar('\n');
		}
	}
	
}

int main () {
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
	Project::MAIN();
}

posted @ 2019-09-20 23:23  Ilverene  阅读(357)  评论(0编辑  收藏  举报