1025D - Recovering BST - CodeForces Solution


brute force dp math number theory trees *2100

Please click on ads to support us..

Python Code:

from math import gcd
import sys
readline=sys.stdin.readline


N=int(readline())
A=list(map(int,readline().split()))
graph=[0]*N
for i in range(N):
    for j in range(N):
        if gcd(A[i],A[j])>=2:
            graph[i]|=1<<j
dpL=[0 for l in range(N+1)]
dpR=[0 for l in range(N)]
for l in range(N):
    r=l+1
    dpL[r]|=1<<l
    dpR[l]|=1<<r
for i in range(2,N+1):
    for l in range(N+1-i):
        r=l+i
        x=(1<<r-l-1)-1
        if (graph[l]>>l+1)&(dpR[l+1]>>l+2)&(dpL[r]>>l+1)&x:
            dpL[r]|=1<<l
        if (graph[r-1]>>l)&(dpR[l]>>l+1)&(dpL[r-1]>>l)&x:
            dpR[l]|=1<<r
if dpR[0]>>1&dpL[N]&((1<<N)-1):
    ans="Yes"
else:
    ans="No"
print(ans)

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

const int mod=998244353;
const int N=705;
const int M=2;
 
bool f[N][N][M],cnm[N][N];
int a[N];

void run()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)	scanf("%d",&a[i]);
	for(int i=0;i<=n+1;i++)
		for(int j=0;j<=n+1;j++)
			if(__gcd(a[i],a[j])!=1)	cnm[i][j]=true;
	for(int i=1;i<=n;i++)
	{
		if(cnm[i][i-1])	f[i][i][0]=true;
		if(cnm[i][i+1])	f[i][i][1]=true;
	}
	for(int len=2;len<=n;len++)
	{
		for(int l=1;l+len-1<=n;l++)
		{
			int r=l+len-1;
			for(int k=l;k<r;k++)
			{
				f[l][r][0]|=(f[l][k][0]&f[k+1][r][0])|(f[l][r-1][1]&cnm[l-1][r]);
				f[l][r][1]|=(f[l][k][1]&f[k+1][r][1])|(f[l+1][r][0]&cnm[l][r+1]);
			}
		}
	}

	if(f[1][n][0]|f[1][n][1])	puts("Yes");
	else						puts("No");
}
 
int main()
{
	int T=1;
//	scanf("%d",&T);
	while(T--)	run(); 
	return 0;
}
/*

*/

 					 	 		 		 		 	  	 		 				


Comments

Submit
0 Comments
More Questions

230B - T-primes
630A - Again Twenty Five
1234D - Distinct Characters Queries
1183A - Nearest Interesting Number
1009E - Intercity Travelling
1637B - MEX and Array
224A - Parallelepiped
964A - Splits
1615A - Closing The Gap
4C - Registration System
1321A - Contest for Robots
1451A - Subtract or Divide
1B - Spreadsheet
1177A - Digits Sequence (Easy Edition)
1579A - Casimir's String Solitaire
287B - Pipeline
510A - Fox And Snake
1520B - Ordinary Numbers
1624A - Plus One on the Subset
350A - TL
1487A - Arena
1520D - Same Differences
376A - Lever
1305A - Kuroni and the Gifts
1609A - Divide and Multiply
149B - Martian Clock
205A - Little Elephant and Rozdil
1609B - William the Vigilant
978B - File Name
1426B - Symmetric Matrix