您的位置:首页 > 其它

POJ-1144(无向图割顶)

2014-08-13 19:18 239 查看
题目:http://poj.org/problem?id=1144

今天学习了无向图中割顶的判断方法:

(1)对于根节点,如果它有多于1个孩子的话,这个根节点就是割顶,否则不是;

(2)对于非根节点u,如果它有一个孩子v,v和v的后代都没有反向边指向u的祖先节点,则u是割顶。

由于这个题需要判断行尾,于是乎先用了istringstream抽取的方法,没想到耗时这么久:



#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
#define MAX     100

int N, cut, dfsClock, pre[MAX];
vector<int> neighboursOf[MAX];

int dfs(int x, int fa)
{
bool isCut = false;
int lowx, y, lowy, children = 0;
const vector<int>& v = neighboursOf[x];

lowx = pre[x] = ++dfsClock;
for(int i = 0, n = v.size(); i < n; ++i){
y = v[i];
if(pre[y]){
if(y != fa) lowx = min(lowx, pre[y]);
}
else{
++children;
lowy = dfs(y, x);
if(lowy >= pre[x]) isCut = true;
lowx = min(lowx, lowy);
}
}
if(!fa && children < 2) isCut = false;
if(isCut) ++cut;

return lowx;
}
int solve()
{
dfsClock = cut = 0;
dfs(1, 0);
return cut;
}
bool prepare()
{
cin >> N;
if(!N) return false;

for(int i = 1; i <= N; ++i){
neighboursOf[i].clear();
pre[i] = 0;
}
int x, y;
string line;
while(cin >> x, x){
getline(cin, line);
istringstream sin(line);
while(sin >> y){
neighboursOf[x].push_back(y);
neighboursOf[y].push_back(x);
}
}
return true;
}

int main()
{
ios::sync_with_stdio(false);
while(prepare()) cout << solve() << "\n";
return 0;
}
试了下自己读取整数,果然效率提高不少:



#include <cstdio>
#include <cctype>
#include <vector>
#include <algorithm>
using namespace std;
#define MAX     100

int N, cut, dfsClock, pre[MAX];
vector<int> neighboursOf[MAX];

int dfs(int x, int fa)
{
bool isCut = false;
int lowx, y, lowy, children = 0;
const vector<int>& v = neighboursOf[x];

lowx = pre[x] = ++dfsClock;
for(int i = 0, n = v.size(); i < n; ++i){
y = v[i];
if(pre[y]){
if(y != fa) lowx = min(lowx, pre[y]);
}
else{
++children;
lowy = dfs(y, x);
if(lowy >= pre[x]) isCut = true;
lowx = min(lowx, lowy);
}
}
if(!fa && children < 2) isCut = false;
if(isCut) ++cut;

return lowx;
}
int solve()
{
dfsClock = cut = 0;
dfs(1, 0);
return cut;
}
bool readInt(int& n)
{
int c = getchar();
n = c - '0';
while(c = getchar(), isdigit(c)) n = n * 10 + c - '0';
if(c == '\n') return true;
return false;
}
bool prepare()
{
scanf("%d", &N);
if(!N) return false;
else while(getchar() != '\n');

for(int i = 1; i <= N; ++i){
neighboursOf[i].clear();
pre[i] = 0;
}
int x, y;
bool endOfLine;
while(readInt(x), x){
endOfLine = false;
while(!endOfLine){
endOfLine = readInt(y);
neighboursOf[x].push_back(y);
neighboursOf[y].push_back(x);
}
}
return true;
}

int main()
{
while(prepare()) printf("%d\n", solve());
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: