PAT A1032 && PAT A1034
A1032 我……不知道错在哪里了……
直接贴个原答案吧……
#include <cstdio>
const int maxn = 100010;
struct Node {
char data;
int next;
bool vis;
} node[maxn];
int main() {
for(int i = 0; i < maxn; ++i) {
node[i].vis = false;
}
int s1, s2, n;
scanf("%d%d%d", &s1, &s2, &n);
for(int i = 0; i < n; ++i) {
int address, next;
char data;
scanf("%d %c %d", &address, &data, &next);
node[address].data = data;
node[address].next = next;
}
int p;
for(p = s1; p != -1; p = node[p].next) {
node[p].vis = true;
}
for(p = s2; p != -1; p = node[p].next) {
if(node[p].vis) {
break;
}
}
if(p == -1) {
printf("-1\n");
} else {
printf("%05d\n", p);
}
return 0;
}
这个for循环比较有意思 for(p = s1; p != -1; p = node[p].next)
A1034我写了个只有四分的答案哈哈哈哈哈……参考答案
#include <iostream>
#include <map>
#include <string>
#define MAXN 2005
using namespace std;
int N, K, cou = 0; //cou来记录结点的总数
int G[MAXN][MAXN] = { 0 }; //使用邻接矩阵来存储图
int weight[MAXN] = { 0 };
bool visit[MAXN] = { false };
map<int, string> intToString; //注意此处的设置可不用使用hash
map<string, int> stringToInt;
map<string, int> gang;
int convert(string str) { //设置结点名称string类型与int类型的对应
if (stringToInt.find(str) != stringToInt.end()) {
return stringToInt[str];
}
else {
intToString[cou] = str;
stringToInt[str] = cou;
cou++;
}
return stringToInt[str];
}
void DFS(int now, int &head, int &numMember, int &totalWeight) { //注意此处为引用
visit[now] = true;
numMember++;
if (weight[now] > weight[head]) {
head = now;
}
for (int i = 0; i < cou; i++)
{
if (G[now][i] > 0)
{ //因为可能有环的出现,以免漏掉某条边,故先考虑是否有边来累加权重
totalWeight += G[now][i]; //集团团伙的总值upup!
G[now][i] = G[i][now] = 0; //累加后需要将权重设为0防止重复累加
if (!visit[i])
{
DFS(i, head, numMember, totalWeight);
}
}
}
return;
}
void solve() {
int head;
int numMember, totalWeight;
for (int i = 0; i < cou; i++)
{
if (!visit[i])
{
head = i;
numMember = totalWeight = 0;
DFS(i, head, numMember, totalWeight);
}
if (numMember > 2 && totalWeight > K) {
gang[intToString[head]] = numMember;
}
}
return;
}
int main() {
string str_1, str_2;
int w, v_1, v_2;
cin >> N >> K;
for (int i = 0; i < N; i++) {
cin >> str_1 >> str_2 >> w;
v_1 = convert(str_1);
v_2 = convert(str_2);
weight[v_1] += w;
weight[v_2] += w;
G[v_1][v_2] += w;
G[v_2][v_1] += w;
}
solve();
cout << gang.size() << endl;
map<string, int>::iterator it;
for (it = gang.begin(); it!=gang.end(); it++) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
DFS!!!我的死穴!!
遍历连通块用DFS!!
遍历连通块用DFS!!
遍历连通块用DFS!!