POJ 2132

我早上调了一个早上,下午才发现把e=edge[e].next写成edge[e].next了。。。

这题直接DFS,一个剪枝是,当当前的最大质因数是最小公倍数的因数时,不用搜索

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <string.h>
#define LL __int64
using namespace std;
const int N=30;
struct Edge{
	int u,v,w;
	int next;
}edge[800];
int tot,n;
LL res;
int head[N];
bool vis[N];


LL gcd(LL a,LL b){
	if(b==0) return a;
	return gcd(b,a%b);
}

LL lcm(LL a,LL b){
	return a*b/gcd(a,b);
}

void dfs(LL g,int u){
	if(u==2){
		res=lcm(g,res);
		return ;
	}
	int v; LL tmp;
	for(int e=head[u];e!=-1;e=edge[e].next){
		v=edge[e].v;
		if(!vis[v]){
			vis[v]=true;
			tmp=gcd(g,edge[e].w);
			if(res%tmp)
			dfs(tmp,v);
			vis[v]=false;
		}
	}
}

void addedge(int u,int v,int w){
	edge[tot].u=u;
	edge[tot].v=v;
	edge[tot].w=w;
	edge[tot].next=head[u];
	head[u]=tot++;
}

int main(){
	while(scanf("%d",&n)!=EOF){
		int tmp;
		memset(head,-1,sizeof(head));
		tot=0;
		res=1;
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				scanf("%d",&tmp);
				if(tmp>0){
					addedge(i,j,tmp);
				}
			}
		}
		memset(vis,false,sizeof(vis));
		vis[1]=true;
		for(int e=head[1];e!=-1;e=edge[e].next){
			vis[edge[e].v]=true;
			dfs(edge[e].w,edge[e].v);
			vis[edge[e].v]=false;
		}
		printf("%I64d
",res);
	}
	return 0;
}
	

  

原文地址:https://www.cnblogs.com/jie-dcai/p/4293367.html