Codeforces Round #479 (Div. 3)D. Divide by three, multiply by two

D. Divide by three, multiply by two

题目链接-D. Divide by three, multiply by two
在这里插入图片描述
在这里插入图片描述
题目大意
有一个长度为 n n 的序列 a n an ,要求你将这个数列重排成一个排列 p n pn ,使得对于任意的 p i pi p i × 2 = p i + 1 p_i×2=p_{i+1} 或者 p i ÷ 3 = p i + 1 p_i÷3=p_{i+1}

解题思路
d f s dfs或拓扑序列

d f s dfs : 搜素每一步应该放哪些数,只要满足 p i × 2 = p i + 1 p_i×2=p_{i+1} 或者 p i ÷ 3 = p i + 1 p_i÷3=p_{i+1} 即可放

拓扑序列 :根据 p i × 2 = p i + 1 p_i×2=p_{i+1} 或者 p i ÷ 3 = p i + 1 p_i÷3=p_{i+1} 连边建图,再跑一遍裸的拓扑排序即可

具体操作见代码

附上代码

  1. 爆搜
#pragma GCC optimize("-Ofast","-funroll-all-loops")
//#pragma GCC diagnostic error "-std=c++11"
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
const double PI=acos(-1.0);
const double e=exp(1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e5+10;
typedef long long ll;
typedef pair<int,int> PII;
typedef unsigned long long ull;
int n,a[150],vis[150],v[150];
bool flag;
void dfs(int x,int cnt){//cnt用来记录步数
	if(cnt==n&&!flag){//如果已经找到序列直接输出
		for(int i=1;i<=n;i++)
			cout<<v[i]<<" ";
		flag=1;//标记,防止输出多种情况
		return ;
	}
	vis[x]=1;
	for(int i=1;i<=n;i++){
		if(!vis[i]&&(v[cnt]*2==a[i]||a[i]*3==v[cnt])){
			v[cnt+1]=a[i];
			dfs(i,cnt+1);
		}
	}
	vis[x]=0;//回溯
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	cin>>n;
	for(int i=1;i<=n;i++)
		cin>>a[i];
    for(int i=1;i<=n;i++){//搜索每一个点
    	memset(vis,0,sizeof vis);
    	v[1]=a[i];
		dfs(i,1);//深搜
	}
	return 0;
}

  1. 拓扑序列
#pragma GCC optimize("-Ofast","-funroll-all-loops")
//#pragma GCC diagnostic error "-std=c++11"
#include<bits/stdc++.h>
#define int long long
#define lowbit(x) (x &(-x))
#define endl '\n'
using namespace std;
const int INF=0x3f3f3f3f;
const int dir[4][2]={-1,0,1,0,0,-1,0,1};
const double PI=acos(-1.0);
const double e=exp(1.0);
const double eps=1e-10;
const int M=1e9+7;
const int N=1e5+10;
typedef long long ll;
typedef pair<int,int> PII;
typedef unsigned long long ull;
int n,edge[110][110],in[110],a[110];
queue<int> q;
vector<int> v;//村答案
void topsort(){//拓扑排序
	for(int i=1;i<=n;i++){
		if(in[i]==0)//将入读为0的点
			q.push(i);//存入队列
	}
	while(!q.empty()){
		int u=q.front();
		q.pop();//选一个入度为0的点出队
		v.push_back(u);//存相应数字对应的下标
		for(int i=1;i<=n;i++){
			if(edge[u][i]){
				in[i]--;//邻接点入度减一 
				if(!in[i])
					q.push(i);//入度为0入队
			}
		} 
	}
	for(int i=0;i<n;i++)
		cout<<a[v[i]]<<" ";//输出答案
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	cin>>n;
	for(int i=1;i<=n;i++)
		cin>>a[i];
    for(int i=1;i<=n;i++){
    	for(int j=1;j<=n;j++){
    		if(a[i]*2==a[j]||(a[i]%3==0&&a[i]/3==a[j])){
    			edge[i][j]=1;//连边
    			in[j]++;//记录入度
			}
		}
	}
	topsort();
	return 0;
}
发布了175 篇原创文章 · 获赞 15 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Fiveneves/article/details/105433153