【思维/DP】HDU6016Count the Sheep【BestCoder Round #92】

来源:互联网 发布:js eval函数 编辑:程序博客网 时间:2024/05/21 17:36

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6016

方法一(思维):四只羊,中间开始枚举;

#include<bits/stdc++.h>using namespace std;const int N=100005;int a[N],b[N],bb[N];int main(){    int t,n,m,k;    cin.sync_with_stdio(false);    cin>>t;    while(t--){        memset(a,0,sizeof(a));        memset(b,0,sizeof(b));        memset(bb,0,sizeof(b));        vector<int>c[N];        for(int i=0;i<N;i++) c[i].clear();        cin>>n>>m>>k;        for(int i=0;i<k;i++){            cin>>a[i]>>b[i];            bb[b[i]]++;    //  和女羊i有关系的男羊的个数;            c[a[i]].push_back(b[i]); //  和男羊a[i]有关系的母羊;        }        long long ans=0;        //  男羊1-女羊1-男羊2-女羊2        for(int i=1;i<=n;i++){       //  枚举男羊2;            int tmp=c[i].size(); //  关系女羊的个数;            for(int j=0;j<tmp;j++){ //  枚举女羊1                ans+=(tmp-1)*(bb[c[i][j]]-1);   //  女羊2*男羊1;            }        }        cout<<ans*2<<endl;    }    return 0;}

方案二(DP):dp[a/b][j]=dp[a/b][j]+dp[b/a][j-1]-dp[a/b][j-2];

#include<bits/stdc++.h>using namespace std;const int N=100005;int a[N],b[N],bb[N];int dp[N][5];   //  从i羊开始排第j只羊的方案数;int main(){    int t,n,m,k;    cin.sync_with_stdio(false);    cin>>t;    while(t--){        memset(a,0,sizeof(a));        memset(b,0,sizeof(b));        memset(dp,0,sizeof(dp));        cin>>n>>m>>k;        for(int i=0;i<k;i++) cin>>a[i]>>b[i];        long long ans=0;        for(int i=1;i<=m;i++)    //  初始化母羊走第一步            dp[i][1]=1;        for(int i=0;i<k;i++)    //  从a[i]走第二步有几条路            dp[a[i]][2]+=dp[b[i]][1];        for(int i=0;i<k;i++)    //  从b[i]走第三步有几条路            dp[b[i]][3]+=dp[a[i]][2]-dp[b[i]][1];        for(int i=0;i<k;i++)    //  第四步            dp[a[i]][4]+=dp[b[i]][3]-dp[a[i]][2]+1;        for(int i=1;i<=n;i++)   //  枚举公羊走第四步的方案数;            ans+=dp[i][4];        cout<<ans*2<<endl;    }    return 0;}