vendredi 2 janvier 2015

Using Permutation in algorithms


I am trying to solve this


A school has N students, numbered from 1 to N. Each student wears a T shirt of some color. The T shirt of the ith student is of color Ci. The teachers of the school want to organize a parade. In the parade, there will be some students standing in a straight line in increasing order of height. The number of students in the line should be atmost M and atleast 1. Your job is to calculate the number of distinct parades that can be organised.


Two parades are said to be distinct if the sequence made by colors of T-shirts worn by students are different.


For each student i, you are given one student Li such that height(Li) < height (i). Li for the shortest student will be 0. The height of all students are distinct.


I found this CODE:



int main()
{
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--)
{
int N,i,M,P;
pair<int,int> a[1001];
int hash[1001]={0},start=0;
int colors[1001],done=1;
cin>>N>>M;
for(i=1;i<=N;i++)
{
cin>>a[i].first>>a[i].second;

hash[a[i].first]=i;
if(a[i].first==0)
start=i;
}

long long sum=((long long)N*(N+1))/2;
while(start!=0)
{

colors[done]=start;
sum-=start;

start=hash[start];

done++;
}
colors[done]=sum;
done++;
// cout<<"array is "<<endl;
for(i=1;i<=N;i++)
{
colors[i]=a[colors[i]].second;

// cout<<colors[i]<<" ";
}
// cout<<endl;
int last[101];
for(i=0;i<=100;i++)
last[i]=-1;
long long dp[1001][1001]={0};


dp[0][0]=1;
bool overflow=false;
for(i=1;i<=N;i++)
{


dp[i][0]+=dp[i-1][0];

for(int j=1;j<=M;j++)
{
dp[i][j]+=dp[i-1][j];
dp[i][j]+=dp[i-1][j-1];
dp[i][j]%=MOD;
}
if(last[colors[i]]!=-1)
{


for(int j=1;j<=M;j++)
{
dp[i][j]-=dp[last[colors[i]]-1][j-1];
if(dp[i][j]<0)
dp[i][j]+=MOD;
else
dp[i][j]%=MOD;
}
}



last[colors[i]]=i;
}
sum=0;
for(i=1;i<=M;i++)
{
sum+=dp[N][i];
sum%=MOD;
}


cout<<sum<<endl;
}
return 0;
}


Please Help me to understand what is the approach behind this , How the algorithm is working , I can't understand It ?





Aucun commentaire:

Enregistrer un commentaire