标签:建图
Description
You have won a collection of tickets on luxury cruisers. Each ticket can be used only once, but can be used in either direction between the 2 different cities printed on the ticket. Your prize gives you free airfare to any city to start your cruising, and free airfare back home from wherever you finish your cruising.
You love to sail and don‘t want to waste any of your free tickets. How many additional tickets would you have to buy so that your cruise can use all of your tickets?
Now giving the free tickets you have won. Please compute the smallest number of additional tickets that can be purchased to allow you to use all of your free tickets.
Input
There is one integer T (T≤100) in the first line of the input.
Then T cases, for any case, the first line contains 2 integers n, m (1≤n, m≤100,000). n indicates the identifier of the cities are between 1 and n, inclusive. m indicates the tickets you have won.
Then following m lines, each line contains two integers u and v (1≤u, v≤n), indicates the 2 cities printed on your tickets, respectively.
Output
Sample Input
Sample Output
#include <stdio.h> #include <algorithm> #include <iostream> #include <string.h> #include <string> #include <math.h> using namespace std; #define MAXN 100000 + 1000 int vis[MAXN],jiou[MAXN][2],head[MAXN],du[MAXN]; int n,m; int tol; struct Edge{ int u,v,next; }edge[MAXN*2]; void addedge(int u,int v){//建图 edge[tol].u = u; edge[tol].v = v; edge[tol].next = head[u]; head[u]=tol++; edge[tol].u = v; edge[tol].v = u; edge[tol].next = head[v]; head[v] = tol++; } void DFS(int u,int pre,int num){ vis[u] = 1; if(du[u]%2 == 0){ jiou[num][0]++; } else{ jiou[num][1]++; } for(int i=head[u];i!=-1;i=edge[i].next){ int v = edge[i].v; if(vis[v]==1 || v==pre){ continue; } DFS(v,u,num); } } int main(){ int T; int a,b; while(~scanf("%d",&T)){ while(T--){ scanf("%d%d",&n,&m); memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); memset(jiou,0,sizeof(jiou)); memset(du,0,sizeof(du)); tol = 0; for(int i=0;i<m;i++){ scanf("%d%d",&a,&b); addedge(a,b); //addedge(b,a); du[a]++; du[b]++; } int s = 0;//有几个图块 for(int i=0;i<n;i++){ if(vis[i]==0 && du[i]!=0){ DFS(i,-1,s++); } } int sum = s-1; for(int i=0;i<s;i++){ if(jiou[i][1] > 2){ sum+=(jiou[i][1]-2)/2; } } printf("%d\n",sum); } } return 0; }
标签:建图
原文地址:http://blog.csdn.net/zcr_7/article/details/41850509