PAT1013. Battle over Cities (adjacency matrix, adjacency table, DFS separately)

Source: Internet
Author: User

Using different graph storage structure adjacency matrix, adjacency table respectively Dfs, I think I am lonely, should try and check set, see can use and check set of DFS,BFS instead of ... Scared and checked.

Adjacency Matrix DFS

#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=1001;
Int G[MAXN][MAXN];
int n,tmp;
BOOL VIS[MAXN];
void Dfs (int v)
{
Vis[v]=true;
for (int i=1;i<=n;i++)
{
if (!vis[i]&&g[v][i]>0) DFS (i);
}
}
int Dfstra ()
{
int i;
Fill (vis,vis+maxn,false);
int cnt=0;
for (i=1;i<=n;i++)
if (g[tmp][i]>0) g[tmp][i]=g[i][tmp]=-1;
for (i=1;i<=n;i++)
{
if (!vis[i]&&i!=tmp)
{
Dfs (i);
cnt++;
}
}
for (i=1;i<=n;i++)
if (g[tmp][i]<0) g[tmp][i]=g[i][tmp]=1;
return cnt-1;
}
int main ()
{
Freopen ("Input.txt", "R", stdin);
int i,j,m,k;
while (scanf ("%d%d%d", &n,&m,&k)!=eof)
{
int a, b;
Fill (g[0],g[0]+maxn*maxn,0);
for (i=0;i<m;i++)
{
scanf ("%d%d", &a,&b);
G[a][b]=g[b][a]=1;
}
for (i=0;i<k;i++)
{
scanf ("%d", &tmp);
printf ("%d\n", Dfstra ());
}
}
return 0;
}

adjacency Table Dfs

#include <cstdio>
#include <vector>
#include <algorithm>
using namespace Std;
const int maxn=1001;
Vector<int >g[maxn];
BOOL VIS[MAXN];
int n,cur;
void Dfs (int v)
{
Vis[v]=true;
for (int i=0;i<g[v].size (); i++)
{
int t=g[v][i];
if (!vis[t]&&t!=cur) DFS (t);
}
}
int Dfstra ()
{
int i;
Fill (vis,vis+maxn,false);
int cnt=0;
for (i=1;i<=n;i++)
{
if (!vis[i]&&i!=cur)
{
DFS (i);
cnt++;
}
}
return cnt-1;
}
int main ()
{
Freopen ("Input.txt", "R", stdin);
int i,j,m,k;
while (scanf ("%d%d%d", &n,&m,&k)!=eof)
{
int A, B;
for (i=0;i<m;i++)
{
scanf ("%d%d", &a,&b);
G[a].push_back (b);
G[b].push_back (a);
}
for (i=0;i<k;i++)
{
scanf ("%d", &cur);
printf ("%d\n", Dfstra ());
}
}
return 0;
}

PAT1013. Battle over Cities (adjacency matrix, adjacency table, DFS separately)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.