这个题一开始用了dfs,因为蓝桥杯的数据太水了,然后就过了。但是之前做过类似的题,用枚举来做的,然后就是可以避免超时
//dfs
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <sstream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct node
{
int to,pre;
};
int h=0,ans=0;
node e[200010];
int head[10005];
void add(int a,int b)
{
e[h].to=b;e[h].pre=head[a];head[a]=h;
h++;
}
int vis[10005];
int start=0;
void dfs(int bg,int time1)
{
if(time1==3){
ans++;
return ;
}
for(int i=head[bg];i>-1;i=e[i].pre)
{
node t=e[i];
if(time1==2&&t.to==start)
{
ans++;
continue;}
if(!vis[t.to])
{
vis[t.to]=1;
dfs(t.to,time1+1);
vis[t.to]=0;
}
}
}
int main(int argc, char *argv[]) {
int n,m;
scanf("%d %d",&n,&m);
memset(head,-1,sizeof(head));
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d %d",&a,&b);
add(a,b);
add(b,a);
}
for(int i=1;i<=n;i++)
{
start=i;
memset(vis,0,sizeof(vis));
vis[i]=1;
dfs(i,0);
}
printf("%d\n",ans);
return 0;
}
//枚举
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <sstream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
struct node
{
int to,pre;
};
set<pair<int ,int > > t;
int h=0,ans=0;
node e[200010];
int head[10005];
void add(int a,int b)
{
e[h].to=b;e[h].pre=head[a];head[a]=h;
h++;
}
int start=0;
int main(int argc, char *argv[]) {
int n,m;
scanf("%d %d",&n,&m);
memset(head,-1,sizeof(head));
for(int i=0;i<m;i++)
{
int a,b;
scanf("%d %d",&a,&b);
add(a,b);
add(b,a);
t.insert(pair<int ,int > (a,b));
}
int sum=0;
set<pair<int ,int > > ::iterator it;
for(it=t.begin();it!=t.end();it++)
{
pair< int,int > temp=*it;
int a=temp.first,b=temp.second;//这个.first不要记错啦啦啦
int ans1=0,ans2=0;
for(int i=head[a];i>-1;i=e[i].pre)
if(e[i].to!=b) ans1++;
for(int i=head[b];i>-1;i=e[i].pre)
if(e[i].to!=a) ans2++;
sum+=ans1*ans2;
}
printf("%d\n",sum*2);
return 0;
}