hdu 5438 Ponds DFS
#include<bits/stdc++.h>
using namespace std;
const int N=10000+5;
typedef long long ll;
struct Edge
{
int u,v,use;
};
vector<Edge>edge;
vector<int>g[N];
int n,m,a[N],in[N],cnt;
ll sum;
void Addedge(int u,int v)
{
in[v]++;in[u]++;
Edge tp;
tp.u=u;tp.v=v;tp.use=1;
edge.push_back(tp);
g[u].push_back(edge.size()-1);
g[v].push_back(edge.size()-1);
}
int dfs(int u)
{
int i,v;
in[u]=0;
sum+=a[u];
cnt++;
for(i=0; i<g[u].size(); i++)
{
if(edge[g[u][i]].use==0) continue;
else edge[g[u][i]].use=0;
if(edge[g[u][i]].u==u) v=edge[g[u][i]].v;
else v=edge[g[u][i]].u;
if(in[v]==0) continue;
dfs(v);
}
}
int main()
{
int _,u,v,i;
ll ans;
scanf("%d",&_);
while(_--)
{
scanf("%d%d",&n,&m);
edge.clear();
for(i=0; i<n; i++)
g[i].clear();
for(i=0; i<n; i++)
scanf("%d",&a[i]);
memset(in,0,sizeof(in));
for(i=0; i<m; i++)
{
scanf("%d%d",&u,&v);
Addedge(u-1,v-1);
}
stack<int>st;
for(i=0; i<n; i++)
if(in[i]==1)
st.push(i);
while(!st.empty())
{
u=st.top();
in[u]=0;
st.pop();
for(i=0; i<g[u].size(); i++)
{
if(edge[g[u][i]].use==0) continue;
else edge[g[u][i]].use=0;
if(edge[g[u][i]].u==u) v=edge[g[u][i]].v;
else v=edge[g[u][i]].u;
//printf("%d\n",v);
in[v]--;
if(in[v]==1) st.push(v);
}
}
ans=0;
for(i=0; i<n; i++)
{
if(in[i]!=0)
{
cnt=0;
sum=0;
dfs(i);
if(cnt%2==1) ans+=sum;
}
}
printf("%lld\n",ans);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。http://xiang578.top/