Domino

18/11/2010 § Leave a comment

Enunt:Se dau n piese de domino.Fiecare piesa poate fi rotita cu 180 de grade.Sa se determine subsiruri de piese de lungime maxima astfel incat oricare doua piese alaturate sa aiba un numar in comun.

Exemplu:

domino.in                                                          cout:

5 6                                                                      6 5
1 1                                                                       5 2
2 5                                                                      2 3
3 2                                                                     3 5
1 5                                                                      5 5
6 4                                                                     5 2
5 1
5 3
2 1
1 4
5 5
5 2
3 3

Algoritm:

#include<iostream.h>
#include<fstream.h>
typedef struct{int first,sec;}PIESA;
PIESA v[100];
int d[2][100],poz[2][100],n;
void citire()
{
n=0;
ifstream f(“domino.in”);
while(!f.eof())f>>v[++n].first>>v[n].sec;
f.close();
}
void dinamica()
{
int i,j,max1,max0,p0,p1;
d[0][n]=d[1][n]=0;
poz[0][n]=poz[1][n]=0;
for(i=n-1;i>=1;i–)
{max0=max1=0;
p0=p1=0;
for(j=i+1;j<=n;j++)
{if(v[i].sec==v[j].first && d[0][j]>max0){max0=d[0][j];
p0=j;}
if(v[i].sec==v[j].sec && d[1][j]>max0){max0=d[1][j];
p0=j;}
if(v[i].first==v[j].sec && d[1][j]>max1){max1=d[1][j];
p1=j;
if(v[i].first==v[j].first && d[0][j]>max1){max1=d[0][j];
p1=j;}
}
d[0][i]=max0+1;
d[1][i]=m
poz[0][i]=p0;
poz[1][i]=p1;}
}
void afisare()
{
int k,p,aux,i,max=0;
for(i=1;i<=n;i++){if(d[0][i]>max){max=d[0][i];k=0;p=i;}
if(d[1][i]>max){max=d[1][i];k=1;p=i;}
}
if(k==0){cout<<v[p].first<<” “<<v[p].sec<<”\n”;aux=v[p].sec;}
else {cout<<v[p].sec<<” “<<v[p].first<<”\n”;aux=v[p].first;}
p=poz[k][p];
while(p>0){if(aux==v[p].first){cout<<v[p].first<<” “<<v[p].sec<<”\n”;
k=0;aux=v[p].sec;}
else {cout<<v[p].sec<<” “<<v[p].first<<”\n”;
k=1;aux=v[p].first;}
p=poz[k][p];}
}
int main()
{
int k,p,i,max=0;
citire();
dinamica();
for(i=1;i<=n;i++){if(d[0][i]>max){max=d[0][i];k=0;p=i;}
if(d[1][i]>max)max=d[1][i];k=1;p=i;}
cout<<max<<”\n”;
afisare();
return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Domino at crengux.

meta

%d bloggers like this: