Codeforces Round #479 (Div. 3) ---- D. Divide by three, multiply by two (DFS)
阿新 • • 發佈:2019-02-02
題意: 給你一個序列,然後利用這個序列中的元素重新組成一個新的序列,其中每相鄰的兩個元素具有兩種關係的一種,例如x,y
滿足 x/3 = y 或 x*2 = y
思路: 爆搜,對於每一個元素
AC程式碼:
#include<bits/stdc++.h>
using namespace std;
#define rep(i,s,e) for(int i=s;i<=e;i++)
#define rev(i,s,e) for(int i=e;i>=s;i--)
#define all(x) x.begin(),x.end()
#define sz(x) x.size()
#define szz(x) int(x.size()-1)
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int MAXN = 2e5+10;
typedef long long LL;
LL a[105];
LL ans[105];
int n;
int k;
int sum;
map<string,int> m;
void dfs(LL x)
{
if(sum == n)
return;
LL x1 = x/3;
LL x2 = x*2;
int pos1 = lower_bound(a+1 ,a+n+1,x1)-a;
int pos2 = lower_bound(a+1,a+n+1,x2)-a;
char tmp1[25];
char tmp2[25];
if(x1 == a[pos1])
sprintf(tmp1,"%I64d",a[pos1]);
if(x2 == a[pos2])
sprintf(tmp2,"%I64d",a[pos2]);
string t1 = tmp1;
string t2 = tmp2;
if(m[t1] == 1)
{
m[t1] = 0 ;
ans[k++] = x1;
sum++;
dfs(x1);
}
else if(m[t2] == 1)
{
m[t2] = 0;
ans[k++] = x2;
sum++;
dfs(x2);
}
}
void init()
{
rep(i,1,n)
{
char tmp[25];
sprintf(tmp,"%I64d",a[i]);
string t = tmp;
m[t] = 1;
}
}
int main()
{
#ifdef LOCAL
freopen("in.txt","r",stdin);
#endif // LOCAL
ios_base::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n;
rep(i,1,n) cin>>a[i];
sort(a+1,a+n+1);
int flag = 0;
rep(i,1,n)
{
k = 0;
sum = 0;
m.clear();
init();
fill(ans,ans+n,0);
ans[k++] = a[i];
char tmp[25];
sprintf(tmp,"%I64d",a[i]);
string t = tmp;
m[t] = 0;
sum++;
dfs(a[i]);
if(sum == n)
{
flag = 1;
break;
}
}
if(flag)
{
rep(i,0,k-1) cout<<ans[i]<<" ";
}
return 0;
}