您的位置:首页 > 大数据 > 人工智能

Flipping Cards 图论 强连通分量 2015 Rocky Mountain Regional Programming Contest

2017-07-06 19:53 746 查看
Problem B Flipping Cards

Accept: 0    Submit: 0

Time Limit: 5000 mSec



 Problem
Description

Mike and his young daughter Jesse are playing a new card game meant

for kids. The rules are quite simple, each player is dealt a hand of cards.

Each card has one picture on each side. They take turns playing cards

and the first one to run out of cards is the winner.



A player’s turn consists of picking a subset of cards from their hand and

laying them on the table. The only rule is that the cards must be placed

on the table such that no two cards are showing the same picture.

Mike thought this was a very appropriate game to play with his kid because of the simple rules. Mike also

liked this game because finding the best strategy is an algorithmically interesting challenge!

Help Mike determine if he can play his entire hand on his first round.



 Input

The first line of the input contains a single positive integer T (T ≤ 10) indicating the number of test cases. Each test case begins with a single integer n denoting the number of cards in Mike’s hand. Here 1 ≤ n ≤ 50 000. Following this are n lines, each describing
a card in Mike’s hand. The pictures on the cards are represented by integers. The ith card is given by two integers pi , qi where 1 ≤ pi , qi ≤ 2n.



 Output

For each test case you should output a single line with the word possible if it ispossible for Mike to play his entire hand in one turn, orimpossible if Mike cannot play his entire hand in one turn.



 Sample
Input

3

3

1 2

1 3

2 3

3

1 2

1 2

1 2

1

1 1



 Sample
Output

possible

impossible

possible

图论题,将每个牌两面的数连边,求强连通分量,同一个分量中点数不能少于边数。因为,每条边代表一张牌,每个点代表一个数字,如果分量中边数多于点数则不能使每张牌都有对应的牌。

#include <cstdio>
#include <iostream>
#include <string.h>
#include <stack>
#include <vector>
#include <queue>
using namespace std;
const int maxn=100005;
int color[maxn],val[maxn],point[maxn],num,cnum;

vector<int> v[maxn];
stack<int> st;
struct Edge{
int from,to;
};
Edge edge[50005];

void dfs(int now) {
color[now]=cnum;
point[cnum]++;
for (int i=0;i<v[now].size();i++) {
if (!color[v[now][i]]) dfs(v[now][i]);
}
}

int main() {
int n,q,t,i,j,x1,x2,y1,y2;
scanf("%d",&t);
for (q=1;q<=t;q++) {
scanf("%d",&n);
for (i=1;i<=n;i++) {
scanf("%d%d",&x1,&y1);
v[x1].push_back(y1);
v[y1].push_back(x1);
edge[i]=(Edge){x1,y1};
}
num=cnum=0;
memset(color,0,sizeof(color));
memset(point,0,sizeof(point));
for (i=1;i<=1e5;i++) {
if (!color[i]) {
cnum++;
dfs(i);
}
}
memset(val,0,sizeof(val));
for (i=1;i<=n;i++) {
if (color[edge[i].from]==color[edge[i].to]) {
val[color[edge[i].from]]++;
}
}
int flag=1;
for (i=1;i<=cnum;i++) {
if (val[i]>point[i]) flag=0;
}
if (flag) printf("possible\n"); else printf("impossible\n");
for (i=1;i<=1e5;i++) v[i].clear();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  图论